POST请求通过一个JSON对象

我创build了一个服务器,服务于客户的发布请求。 我正在使用bodyserver,但得到一些错误

var bodyParser = require('body-parser') var express = require('express'); var app = express(); app.use(bodyParser.json()); app.post('/v3/botstate/:channel/users/:userid', function (req, res) { console.log("hsijdaf"); console.log(req.body); //console.log(req.body); // res.send('Hello POST'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) 

客户如下所示,

 var request = require('request'); request.post({ url: "http://localhost:8081/v3/botstate/webchat/users/siddiq", headers: { "Content-Type": "application/json" }, body: '{"jsonrpc":"2.0","id":"zdoLXrB5IkwQzwV2wBoj","method":"barrister-idl","params":[]}', json:true }, function(error, response, body){ console.log(error); console.log(JSON.stringify(response)); console.log(body); }); 

在运行客户端时出现以下错误,

 E:\TESTING>node exp.js Example app listening at http://:::8081 SyntaxError: Unexpected token " at parse (E:\TESTING\node_modules\body-parser\lib\types\json.js:83:15) at E:\TESTING\node_modules\body-parser\lib\read.js:116:18 at invokeCallback (E:\TESTING\node_modules\body-parser\node_modules\raw-body\index.js:262:16) at done (E:\TESTING\node_modules\body-parser\node_modules\raw-body\index.js:251:7) at IncomingMessage.onEnd (E:\TESTING\node_modules\body-parser\node_modules\raw-body\index.js:307:7) at emitNone (events.js:67:13) at IncomingMessage.emit (events.js:166:7) at endReadableNT (_stream_readable.js:921:12) at nextTickCallbackWith2Args (node.js:442:9) at process._tickCallback (node.js:356:17) 

请帮我解决这个问题。

你已经在客户端设置了Content-Type : application/json ,但是你的POST数据是text/plain ,而不是json 。 这就是为什么body-parser无法parsing它,因为它期望通过header json

尝试删除客户端的body后。

例如

 var request = require('request'); request.post({ url: "http://localhost:8081/v3/botstate/webchat/users/siddiq", headers: { "Content-Type": "application/json" }, body: { "jsonrpc":"2.0", "id":"zdoLXrB5IkwQzwV2wBoj", "method":"barrister-idl", "params":[] }, json:true }, function(error, response, body){ console.log(error); console.log(JSON.stringify(response)); console.log(body); }); 

希望它可以帮助你。