bgu*_*uiz 5 javascript json http-headers node.js express
如果快递bodyParser不会触发,如何在请求中访问POST数据?
var server = express();
server.use(express.bodyParser());
server.post('/api/v1', function(req, resp) {
var body = req.body;
//if request header does not contain 'Content-Type: application/json'
//express bodyParser does not parse the body body is undefined
var out = {
'echo': body
};
resp.contentType('application/json');
resp.send(200, JSON.stringify(out));
});
Run Code Online (Sandbox Code Playgroud)
注意:在ExpressJs中,3.x + req.body不能自动使用,需要bodyParser激活.
如果未设置内容类型标头,是否可以指定默认内容类型application/json并触发bodyParser?
否则是否可以使用这个明确的POST函数中的裸nodejs方式访问POST数据?
(例如req.on('data', function...)
Pet*_*ons 13
你有很多选择,包括自己手动调用快速(连接,真正)中间件函数(真的,去阅读源代码.它们只是函数,并没有让你迷惑的深刻魔法).所以:
function defaultContentTypeMiddleware (req, res, next) {
req.headers['content-type'] = req.headers['content-type'] || 'application/json';
next();
}
app.use(defaultContentTypeMiddleware);
app.use(express.bodyParser());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7421 次 |
| 最近记录: |