2017-01-30 5 views
-2

私はフォームからデータを取得しています。送信ボタンを使用すると、データをnodejsサーバーに送信する必要があります。私は斧を使用してサーバーにデータを送信することができません。また私は何が問題であるかもしれない何かエラーを受け取っていないですか?斧を使用してサーバーにデータを送信できません

import React from 'react'; 
import axios from 'axios'; 
class Createstudent extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = {value: ''}; 

    this.handleChange = this.handleChange.bind(this); 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 

    handleChange(event) { 
    this.setState({value: event.target.value}); 
    } 

    handleSubmit(event) { 
    alert(this.state.value); 

    } 

    componentDidMount(){ 
    axios.post('http://localhost:8080/create',{value:this.state.value}) 
    .then(function(response){ 
     console.log(response); 
    }) 
    } 

    render() { 
    return (
     <form onSubmit={this.handleSubmit}> 
     <label> 
      Name: 
      <input type="text" value={this.state.value} onChange={this.handleChange} /> 
     </label> 
     <input type="submit" value="Submit" /> 
     </form> 
    ); 
    } 
} 

export default Createstudent; 

答えて

0

ポストコールを行う方法以外はすべて componentDidMountはコンポーネントのレンダリングの直後に一度だけ呼び出されるため、これではポストコールを行うことができません。

From React DOCs

はcomponentDidMount()は直ちに が搭載されている構成要素の後に呼び出されます。 DOMノードを必要とする初期化はここに行かなければなりません。 がリモートエンドポイントからデータをロードする必要がある場合、これは がネットワーク要求をインスタンス化するのに適しています。

handleSubmitメソッド内でそのポストコールを書く、それは動作しますが、これを試してみてください。

componentDidMount(){ 

} 

handleSubmit(event) { 
    alert(this.state.value); 
    axios.post('http://localhost:8080/create',{value:this.state.value}) 
     .then(function(response){ 
     console.log(response); 
     }) 
} 
+0

屋を自分のサーバーにその示すだけの花のブラケット –

+0

側に正しく送信された反応から必ずデータを作ることができますかサーバ –

+0

開発者モードのgotoネットワークで、urアプリケーションがリクエストを行うとurlとすべてのパラメータが渡されます。ヘッダのポストコール文字列パラメータをチェックします。エラー。 –

0

私はaxios.posthandleSubmit()から呼び出されるべきだと思います。現在、あなたのコードはcomponentDidMount()のAxiosを使用していますが、これはあなたのReactコンポーネントのライフサイクルで早く(自動的に)トリガーされます。

関連する問題