【问题标题】:Can read data without content-type?可以读取没有内容类型的数据吗?
【发布时间】:2016-08-02 11:21:54
【问题描述】:

如果发送没有 content-type 标头的数据,我可以读取数据吗?

我刚刚尝试用 bodyparser 读取 nodejs,但我无法读取。

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

有什么办法吗?

【问题讨论】:

    标签: javascript java node.js content-type


    【解决方案1】:

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

    【讨论】:

    • 如果您将其标记为解决方案,那就太好了!
    【解决方案2】:

    您需要将内容类型添加为application/json,以便正文解析器将数据解析为json。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多