如何通过假设默认内容类型来解析Express/NodeJ中缺少内容类型的HTTP请求? [英] How to parse HTTP request with a missing content type in Express/ NodeJs, by assuming a default content type?

查看:27
本文介绍了如何通过假设默认内容类型来解析Express/NodeJ中缺少内容类型的HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果快递 bodyParser 没有启动,如何获取请求中的POST数据?

How can I get access to the POST data in a request, if the express bodyParser does not fire?

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));
});

注意:在ExpressJs 3.x +中, req.body 不会自动可用,需要 bodyParser 才能激活.

Note: in ExpressJs 3.x+ req.body is not automatically available, and requires bodyParser to activate.

如果未设置内容类型标头,是否可以将默认内容类型指定为 application/json 并触发 bodyParser ?

If a content type header is not set, is it possible to specify a default content type of application/json and trigger the bodyParser?

否则,可以从该Express POST函数中使用裸nodejs方式访问POST数据吗?

Otherwise is it possible to access the POST data using the bare nodejs way from within this express POST function?

(例如 req.on('data',function ... )

推荐答案

您有很多选择,包括自己手动调用express(连接,实际上)中间件函数(真的,请阅读源代码.它们只是函数和没有任何深奥的魔法可以使您感到困惑.所以:

You have a bunch of options including manually invoking the express (connect, really) middleware functions yourself (really, go read the source code. They are just functions and there is no deep magic to confuse you). So:

function defaultContentTypeMiddleware (req, res, next) {
  req.headers['content-type'] = req.headers['content-type'] || 'application/json';
  next();
}

app.use(defaultContentTypeMiddleware);
app.use(express.bodyParser());

这篇关于如何通过假设默认内容类型来解析Express/NodeJ中缺少内容类型的HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆