我正在使用NodeJS和Express(以及更多类似于mongo、sockets等的东西)开发一个API,但我认为我卡在了一个非常简单的步骤上。 我只是尝试从POST req
对象中获取信息,但在尝试访问req.body
时出现错误。
下面是我的代码:
var express = require('express'),
http = require('http'),
path = require('path'),
fs = require('fs'),
io = require('socket.io');
dynroute = require('dynroute');
var app = express();
app.set('port', process.env.PORT || 3999);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(app.router);
app.use(express.bodyParser());
app.post('/user', function(req, res) {
console.log(JSON.stringify(req.body));
res.send(req.body.self);
});
http.createServer(app).listen(app.get('port'), function ()
{
console.log('App Server is now running at:' + app.get('port'));
});
在console.log(JSON.stringify(req.body));
中,我得到了undefined
,而在res.send(req.body.self);
中,我得到了TypeError: Cannot read property 'self' of undefined
。
我一直在寻找这种类型的错误,通常问题是人们没有包含app.use(express.bodyParser());
中间件,所以我也尝试使用app.use(express.urlencoded());
和app.use(express.json());
,但都不起作用。
如果我执行console.log(req)
,我可以看到整个对象,但当我从客户端进行POST请求时(我将其作为JSON传递),我无法看到body
或任何我传递的内容。
**我知道我可以使用restify
或sails.js
在Node中构建API,但我想自己做所有事情,以便我可以从经验中学习。*
谢谢
编辑:
我必须在app.router
中间件之前放置bodyparser
中间件,这解决了问题!
['user':'kevinblanco']
作为内容传递到我的URL,并使用application/json作为内容类型标头。 - kevinblanco