Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Content-Type: application/octet-stream request in node.js

Tags:

node.js

I have sent the following request from post man to 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

How can I process the above request from node.js and read the request data?

The above request hit my router:

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

I am always getting req.body is {}. But I am expecting:

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
like image 262
P John Raj Avatar asked Oct 31 '14 10:10

P John Raj


1 Answers

I was did following to solve this problem

Fist I add following setting in app level

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

After that When I read data from following code

app.put('api/locations/import', function(req,res){
    'use strict';
    console.log(req.body);
    console.log(req.body.hello);
    res.send(200);
});
like image 87
P John Raj Avatar answered Sep 28 '22 06:09

P John Raj