0

I'm trying to do two different project request. I am request a using request module other project using express but json parse error in the express project

example object

var data= {
    User: {
        ID: 123
    },
    Text: 'hello world'
};

 request.post({
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
            url: "url/test",
            body: JSON.stringify(data)
        }, function (error, response, body) {

            logger.debug("error : ", error);
            logger.debug("body : ", body);

        });

Listen a express project

app.post('/test', function(req, res) {

    try {
        res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
        res.header('Access-Control-Allow-Methods', 'POST');
        res.header('Access-Control-Allow-Headers', 'Content-Type');

        console.log(req.body);
        var x = JSON.parse(req.body);

        res.send(200);

    } catch (error) {

        res.send(200);
    }
});

req.body is

{ '{"User":{"ID":123},"Text":"hello world"}': '' }

erorr is

SyntaxError: Unexpected token o in JSON at position 1

beats extra single quote { '{"User":{"ID":123},"Text":"hello world"}': '' }

Thomas A.
  • 1
  • 1
  • I think its the same issue with this question http://stackoverflow.com/questions/10005939/how-to-consume-json-post-data-in-an-express-application Basically, you need bodyParser to parse the json body – PunNeng Dec 24 '16 at 08:03
  • thanks punneng but bodyparse is on my code – Thomas A. Dec 24 '16 at 16:35

2 Answers2

0

req.body is an object, not a simple string. The Javascript interpreter has already parsed it. This is why you see the mysterious Unexpected token o in JSON at position 1 message, despite there being no "o" in the JSON; JSON.parse is attempting a string operation on a non-string.

Zéychin
  • 4,135
  • 2
  • 28
  • 27
0

you should add some options to your express app config and install body-parser package using npm install body-parser like this:

var bodyParser = require('body-parser');
app.use(bodyParser.json({
keepExtensions: true
}));
app.use(bodyParser.urlencoded());
farhadamjady
  • 982
  • 6
  • 14
  • i 've been trying like this // Body Parser app.use(bodyParser.json()); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); // Body Parser end i will try your method. i write result – Thomas A. Dec 24 '16 at 08:46
  • sorry no change :( – Thomas A. Dec 24 '16 at 08:47
  • use `JSON.parse(JSON.stringify((req.body))` to parsing json value – farhadamjady Dec 24 '16 at 08:55