以下は私のサーバーのコードのhtmlページでnode.jsサーバーはどのようにしてajaxリクエストのデータにアクセスできますか?
/* GET tone. */
router.post('/tone', function(req, res, next) {
console.log("what is the body" + req.body.data);
tone_analyzer.tone({ text: req.body.data }, function(err, tone) {
console.log(req.body.data);
if (err) {
console.log(err);
} else {
res.send(JSON.stringify(tone, null, 2));
}
console.log(req);
});
});
私のAjaxの呼び出しです。
function toneAnalysis(info){
$.ajax({
url: 'http://localhost:3000/tone',
type: 'POST',
data: info,
success: function(res) {
console.log("testing " + info);
},
error: function(xhr, status, errorThrown) {
console.log(status);
}
})
サーバがreq.body.data
を取得できませんでした。それをログに記録しようとすると、常に定義されていません。誰も私にこれを手伝ってもらえますか?ありがとうございました。
更新: The printed req.body after I used body parser
これは単にreq.bodyである必要があります。ログアウトして、それが定義されているかどうかを確認します。 body-parserを使用する必要があります。 –
2番目のコメントでbody parserが必要な場合もありますが、typeof(req.data)を見れば=== 'string'ならJSONの解析が必要な場合があります。 –
http://expressjs.com/en/4x/api.html#req.body –