下面是我的服务器的代码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);
});
});
我的阿贾克斯队在HTML页面中调用。
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。 –
其次,您可能需要body解析器的注释,如果它==='string',也看typeof(req.data),那么您可能需要JSON解析它。 –
http://expressjs.com/en/4x/api.html#req.body –