最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to parse HTTP request with a missing content type in Express NodeJs, by assuming a default content type? - Stac

programmeradmin1浏览0评论

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

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

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

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

(e.g. req.on('data', function...)

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

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

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

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

(e.g. req.on('data', function...)

Share Improve this question edited Jun 4, 2014 at 4:56 bguiz asked Jun 21, 2013 at 4:52 bguizbguiz 28.6k49 gold badges163 silver badges251 bronze badges 2
  • 2 just use req.on('data') or do req.headers['content-type'] = req.headers['content-type'] || 'application/json' before the body parser, but really this is a client error. – Jonathan Ong Commented Jun 21, 2013 at 5:17
  • @JonathanOng thanks. Yes, I know that this is a client error - just trying to work around it. How would I go about doing something before the body parser kicks in? AFAICT, it has already been triggered by the time this express PUT callback function is entered. – bguiz Commented Jun 21, 2013 at 5:37
Add a comment  | 

3 Answers 3

Reset to default 22

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

I use this middleware, before bodyParser kicks in, which may help. It peeks at the first byte of the request stream, and makes a guess. This particular app only really handles XML or JSON text streams.

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

In Express 4.x, had the same problem, whe client was misbehaved and did not send the content type. Passing some configs to express.json() did the trick:

app.use(express.json({inflate: true, strict: false, type: () => { return true; } }));

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论