admin管理员组

文章数量:1421988

I have the next post request:

POST /download HTTP/1.1
Host: localhost:5000
Content-Type: application/json

and the next request payload:

{"blabla":"toto"}

Now, In express module (node.js), I have the next:

app.post("/download", function(req, res){
    var parseJson = JSON.parse(req.body);

});

When I use JSON.parse, it gives me the next error:

SyntaxError: Unexpected token o
    at Object.parse (native)
    at c:\NodeI\node\express.js:161:19
    at callbacks (c:\NodeI\node\node_modules\express\lib\router\index.js:161:37)

What can be the reason? I sent a JSON, why it doesn't parse it?

I have the next post request:

POST /download HTTP/1.1
Host: localhost:5000
Content-Type: application/json

and the next request payload:

{"blabla":"toto"}

Now, In express module (node.js), I have the next:

app.post("/download", function(req, res){
    var parseJson = JSON.parse(req.body);

});

When I use JSON.parse, it gives me the next error:

SyntaxError: Unexpected token o
    at Object.parse (native)
    at c:\NodeI\node\express.js:161:19
    at callbacks (c:\NodeI\node\node_modules\express\lib\router\index.js:161:37)

What can be the reason? I sent a JSON, why it doesn't parse it?

Share Improve this question asked Apr 30, 2014 at 12:52 Or SmithOr Smith 3,62613 gold badges47 silver badges70 bronze badges 16
  • 1 What is console.log(req.body);? – epascarello Commented Apr 30, 2014 at 12:55
  • NO! What does it show in the console. – epascarello Commented Apr 30, 2014 at 12:58
  • @epascarello: Nothing, It shown the error I wrote in the question – Or Smith Commented Apr 30, 2014 at 12:58
  • 1 @OrSmith — Put console.log(req.body) before JSON.parse(req.body) and tell us what the Node.js console (not the browser console) says. – Quentin Commented Apr 30, 2014 at 13:00
  • 1 {blabla: 'toto' } isn't JSON … but it should plain about unexpected token b, not o. – Quentin Commented Apr 30, 2014 at 13:06
 |  Show 11 more ments

1 Answer 1

Reset to default 6

Your JSON has already been parsed by the time it gets to req.body

JSON.parse(req.body); calls toString() on the JavaScript object, gets the string [object Object] and tries to parse that as JSON.

Just use req.body directly instead of running it through JSON.parse.

本文标签: jsonJavaScriptpost gives SyntaxError Unexpected token oStack Overflow