2017-12-22 11 views
0

ReactとNode.jsを学び始めました。私は非常に単純なフォームを作成し、それを伝統的な方法(同期的に、ajaxなし)で学習目的で提出しようとしています。 srcディレクトリ内には、フォーム用のディレクトリと、フォームを送信しているnode.jsファイル用の別のディレクトリ(モデル)があります。私がsubmitをクリックすると、「can not POST /model/controller.js」が表示されます。私は周りにグーグルで見つけて何も見つかりませんでした。基本を取り戻そうとしています。ご協力いただきありがとうございます。シンプルなテストポストが動作しない、node.js

でフォームのSRC /ログインは/ Login.js「

class Login extends React.Component { 
render() { 
    return (
     <form method="POST" action="/../model/controller.js" className="commonform" id="ajaxform" name="ajaxform"> 
     <h2>Please Sign In</h2> 
     <Para class="usernotify" text= "test"/> 
     <Input name="email" /> 
     <Input name="password" /> 
     <Button name="Sign In" id="ajaxSubmit"/> 
     </form> 
    ); 

} 
} 

私が提出していますサーバー・ページ 'のsrc /モデル/ controller.js'

var http = require('http'); 
http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.write('Hello'); 
    res.end(); 
    }).listen(8080); 
+0

にPOSTリクエストを行うには、あなたの行動を変え、ポート8080で別のモジュールとしてあなたのノードのJSを実行しています。 'Node'は最初に、' React'は秒です。私はあなたが両方の使い方を混同していると思います。 –

+0

ここにはたくさんのものがありません。反応形式は、通常のHTML形式とは少し異なります。各フィールドの状態を保持し、イベントを変更して送信し、イベントメソッドをバインドする必要があります。私はあなたが反応form.httpsについて読むことをお勧めします://reactjs.org/docs/forms.html –

答えて

0

と仮定すると、あなたの'src/model/controller.js httpサーバが稼働しており、POSTSリクエストの場合は/model/controllerをリッスンしています。https://reactjs.org/docs/forms.html

class Login extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = {}; 

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


    handleSubmit(event) { 
    // Post your data here using something like axios 
    axios.post('http://localhost/model/controller', { 
     ...your_data 
    }) 
    .then(function (response) { 
     console.log(response); 
    }) 
    .catch(function (error) { 
     console.log(error); 
    }); 


    //prevent form from being submitted automatically 
    event.preventDefault(); 
    } 

    render() { 
    return (
     <form onSubmit={this.handleSubmit}> 
     .... 
     </form> 
    ); 
    } 
} 
0

あなたのコントローラには、サーバーを追加しましたが、postメソッドがありません。このようなものを追加してください。また、あなたのhtmlフォームでアクションを変更する必要が

var express = require('express'); 
var app = express(); 
app.post('/api/users', function(req, res) { 
    var user_id = req.body.id; 
    var token = req.body.token; 

    res.send(user_id + ' ' + token); 
}); 

、それはcontroller.jsのようなJSファイルにすべきではない、それは私の場合は/ API /ユーザであるコントローラのエンドポイントにする必要があります。

私の提案は、私は1でスタートをお勧めしhttp://localhost:8080/api/users

関連する問題