我发誓它几天前正在工作,所以这种行为对我来说真的很奇怪。让我在客户端向您展示我的代码
$(document).ready(function() {
$("button").click(function() {
alert(event.currentTarget.id+"------"+event.currentTarget.value);
$.post( "/vote", {id:event.currentTarget.id,count:event.currentTarget.value}, $(this).serialize(),
function(res) {
}
);
})
})
正如您所看到的,单击按钮后,我尝试将id
和value
传递回服务器。到目前为止,这里的一切都很好,因为我可以在屏幕上看到具有正确ID号和值(Output example -> aaa------23)
的警报弹出窗口。现在看看我的服务器端代码。
app.post('/vote', function(req, res) {
var id = req.body.id;
var count = req.body.count;
console.log("id: " + id);
console.log("count: " + count);
res.sendStatus(200);
res.end();
});
执行到行var id = req.body.id
时,系统返回
TypeError: Cannot read property id of undefined
。
count
会有相同的结果。
我有什么明显的遗失吗?因为我发誓它以前工作过,从那时起我就无法触及这部分代码。谢谢你的帮助。
答案 0 :(得分:0)
确保使用body-parser
并在路线前定义。
npm install body-parser --save
然后在定义路线之前包括它:
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/vote', function(req, res) {
var id = req.body.id;
var count = req.body.count;
console.log("id: " + id);
console.log("count: " + count);
res.sendStatus(200);
res.end();
});