如何在node.js中读取Content-Type:application / octet-stream请求

时间:2014-10-31 10:56:44

标签: node.js

我已经从post man向node.js发送了以下请求:

curl -X PUT -H "Content-Type: application/octet-stream" -H "app_key: dhdw-sdsjdbsd-dsdv-ddd" -H "Authorization: Login jddjd-ddd-ddd-ddd-ddd" -H "Cache-Control: no-cache" -H "Postman-Token: dbee5942-5d54-c1b7-415c-7ddf9cb88cd0" -d 'Code,Name,Parent,Address

root,root,,root
root1,root1,root,root1
root2,root2,root1,root2
root3,root3,root2,root3
root4,root4,root,root4
root5,root5,root4,root5
root6,root6,root,root6
' http://localhost:9000/api/locations/import

如何从node.js处理上述请求并读取请求数据?

以上请求命中了我的路由器:

app.put('api/locations/import', function(req,res){
  'use strict';
  console.log(req.body);
  console.log(req.body.hello);
  res.send(200);
});

我总是req.body{}。但我期待:

root,root,,root
root1,root1,root,root1
root2,root2,root1,root2
root3,root3,root2,root3
root4,root4,root,root4
root5,root5,root4,root5
root6,root6,root,root6

1 个答案:

答案 0 :(得分:1)

我是按照以下方式解决了这个问题

拳头我在应用级别添加以下设置

var getRawBody = require('raw-body');
app.use(function (req, res, next) {
    if (req.headers['content-type'] === 'application/octet-stream') {
        getRawBody(req, {
            length: req.headers['content-length'],
            encoding: req.charset
        }, function (err, string) {
            if (err)
                return next(err);

            req.body = string;
            next();
         })
    }
    else {
        next();
    }
});

之后当我从以下代码中读取数据时

app.put('api/locations/import', function(req,res){
    'use strict';
    console.log(req.body);
    console.log(req.body.hello);
    res.send(200);
});