可以读取没有内容类型的数据

Can read data without content-type?

本文关键字:类型 数据 读取      更新时间:2023-09-26

如果发送没有内容类型头的数据,我可以读取数据吗?

我只是试着用bodysparser在nodejs中阅读,但我无法阅读。

NODEJS总是收到空的请求正文。

有办法吗?

使用body-parser需要指定内容类型,否则express(我认为这就是您正在使用的)将无法读取正文。

您可以随时访问原始主体:

app.use (function(req, res, next) {
    var data='';
    req.setEncoding('utf8');
    req.on('data', function(chunk) { 
       data += chunk;
   });
   req.on('end', function() {
       req.body = data;
       next();
   });
});
app.post('/', function(req, res) {
    // you have set the body before:
    console.log(req.body);
});

您需要将Content类型添加为application/json,以便主体解析器将数据解析为json。