阅读Node.JS中的AJAX postvariables(使用Express)

我试图得到我的节点应用程序中发送的ajax文章的值。 使用这篇文章作为指导,我到目前为止:

在节点中:

var express = require('express'); var app = express(); var db = require('./db'); app.get('/sender', function(req, res) { res.sendfile('public/send.html'); }); app.post('/send_save', function(req, res) { console.log(req.body.id) console.log(req.body.title); console.log(req.body.content); res.contentType('json'); res.send({ some: JSON.stringify({response:'json'}) }); }); app.listen(3000); 

在AJAX方面:

 $('#submit').click(function() { alert('clicked') console.log($('#guid').val()) console.log($('#page_title').val()) console.log($('#page-content').val()) $.ajax({ url: "/send_save", type: "POST", dataType: "json", data: { id: $('#guid').val(), title: $('#page_title').val(), content: $('#page-content').val() }, contentType: "application/json", cache: false, timeout: 5000, complete: function() { //called when complete console.log('process complete'); }, success: function(data) { console.log(data); console.log('process sucess'); }, error: function() { console.log('process error'); }, }); }) 

这个问题是,我不能req.body.id(和任何其他值,如标题或内容),我得到这个错误在节点:

  TypeError: Cannot read property 'id' of undefined 

如果我评论这些电话,阿贾克斯是成功的。 我搞不清楚了。 我忘了什么吗?

你在那里的req对象没有body属性。 看看http://expressjs.com/api.html#req.body

该属性是一个包含parsing的请求主体的对象。 这个特性是由bodyParser()中间件提供的,尽pipe其他的bodyparsing中间件也可以遵循这个约定。 当使用bodyParser()时,此属性默认为{}。

所以,您需要将bodyParser中间件添加到您的express webapp中,如下所示:

 var app = express(); app.use(express.bodyParser()); 

这个问题确实通过包含由jhbuild议的bodyParser中间件来解决。

只要确保访问该答案中提供的url,以访问快速更新的规范: http : //expressjs.com/api.html#req.body

该文档提供了此示例(Express 4.x):

 var app = require('express')(); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded app.use(multer()); // for parsing multipart/form-data app.post('/', function (req, res) { console.log(req.body); res.json(req.body); }) 

为了这个工作,body-parser模块需要分开安装:

https://www.npmjs.com/package/body-parser