2016-12-19 15 views
1

私は、クライアントの投稿要求を処理するサーバーを作成しました。私はJSONオブジェクトによるPOSTリクエスト

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) 

私を助けてください、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) 

}) 

を取得しています問題の解決に

答えて

6

Content-Type : application/jsonをクライアントに設定しましたが、POSTのデータはjsonではなくtext/plainです。だからbody-parserは、jsonからheaderを予想していたので、それを解析できません。

お客様のクライアントで' '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 - コンテンツタイプが明示的に定義されていない状態でjsonをPOSTしている方がいいです( "application/json"を自動的に使用します) –

関連する問題