访问由Node的Expressparsing的JSONstringbodyParser()

问题:parsing的JSON是什么对象?

我成功地发送一个JSONstring到服务器,但我一直无法访问该对象。

客户端脚本,发送JSON:

var loginCredentials= { "username":creds.username, "password":creds.password }; request = $.ajax({ url: "http://127.0.0.1:8080/login", type: "POST", crossDomain: true, data: JSON.stringify(loginCredentials), dataType: "json" }); 

login监听器,等待和据说parsingJSON:

 function listen(){ app.use(express.bodyParser()); app.post('/login', function(req, res) { var util = require('util'); console.log(util.inspect(req.body, false, null)); console.log(req.body.username); }); app.listen(8080, function() { console.log('Server running at http://127.0.0.1:8080/'); }); } 

哪些日志:

 Server running at http://127.0.0.1:8080/ { '{"username":"username1","password":"badpassword"}': '' } undefined 

所以它看起来像我的JSONparsing正确,但我试图通过req.body.username访问它,它不存储在那里。

bodyParser不知道你发送的是JSON。 它假设主体是标准的www-form-urlencoded ,因此将其全部parsing为单个关键字。

相反,发送适当的内容types与您的请求:

 request = $.ajax({ url: "http://127.0.0.1:8080/login", type: "POST", crossDomain: true, data: JSON.stringify(loginCredentials), contentType : 'application/json', dataType: "json" // response type }); 

但是,正如不要在Express.js中使用bodyParser中提到的那样,您可能只使用express.json()中间件。