如何通过假设默认内容类型来解析Express / NodeJ中缺少内容类型的HTTP请求?

时间:2013-06-21 04:52:26

标签: javascript json node.js express http-headers

如果快递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));
});

注意:在ExpressJs中,3.x + req.body不会自动提供,并且需要bodyParser才能激活。

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

否则是否可以使用这个明确的POST函数中的bare nodejs方式访问POST数据?

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

2 个答案:

答案 0 :(得分:13)

你有很多选择,包括自己手动调用快速(连接,真正)中间件函数(真的,去阅读源代码。它们只是函数,没有深刻的魔法让你迷惑)。所以:

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

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

答案 1 :(得分:3)

我使用这个中间件,在bodyParser开始之前,这可能会有所帮助。 它会查看请求流的第一个字节,并进行猜测。 这个特殊的应用程序只能真正处理XML或JSON文本流。

app.use((req,res, next)=>{
    if (!/^POST|PUT$/.test(req.method) || req.headers['content-type']){
        return next();
    }
    if ((!req.headers['content-length'] || req.headers['content-length'] === '0') 
            && !req.headers['transfer-encoding']){
        return next();
    }
    req.on('readable', ()=>{
        //pull one byte off the request stream
        var ck = req.read(1);
        var s = ck.toString('ascii');
        //check it
        if (s === '{' || s==='['){req.headers['content-type'] = 'application/json';}
        if (s === '<'){req.headers['content-type'] = 'application/xml'; }
        //put it back at the start of the request stream for subsequent parse
        req.unshift(ck);
        next();
    });
});