2016-12-19 134 views
1

我已經創建了一個服務器來爲客戶端提供發佈請求。我現在用的是bodyserver,但收到的一些錯誤通過JSON對象的POST請求

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) 

請幫我在解決問題。

回答

6

您已在您的客戶端設置Content-Type : application/json,但您的POST數據爲text/plain,而不是json。這就是爲什麼body-parser未能解析它,因爲它期待jsonheader

在客戶端從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); 
}); 

希望它可以幫助你。

+0

另請參閱:https://stackoverflow.com/a/27190736/7022062 - 沒有明確定義內容類型的POST'ing json有更好的版本(將自動使用「application/json」!) –