2014-01-26 98 views
2

我正在使用Node.js和請求模塊。我正在嘗試發出請求API(restfull),但它沒有正確發送請求。我可以使這項工作在捲曲和Python的請求模塊,但不Node.js的請求模塊:Node.js請求模塊....發送json在主體中用於放置API請求

var request = require('request'); 

token = 'sfgsfsf'; 

var options = { 
    url: 'https://_rest_full_api 
    headers: { 
     'X-Auth-Token': token 
    }, 
    body: { 
     'status' : 'pending' 
    }, 
    json: true, 
    method: 'put' 
}; 

function callback(error, response, body) { 
    if (!error && response.statusCode == 200) { 
     var info = JSON.parse(body); 
     console.log(info); 
     console.log(info); 
    } else { 
     console.log(response.statusCode); 
     console.log(response.body); 
    } 
} 

request(options, callback); 


SyntaxError: Unexpected token o 
    at Object.parse (native) 
    at Request.callback [as _callback] (/home/one/try.js:19:25) 
    at Request.self.callback (/home/one/node_modules/request/request.js:122:22) 
    at Request.EventEmitter.emit (events.js:98:17) 
    at Request.<anonymous> (/home/one/node_modules/request/request.js:888:14) 
    at Request.EventEmitter.emit (events.js:117:20) 
    at IncomingMessage.<anonymous> (/home/one/node_modules/request/request.js:839:12) 
    at IncomingMessage.EventEmitter.emit (events.js:117:20) 
    at _stream_readable.js:920:16 
    at process._tickCallback (node.js:415:13) 

回答

7

設置爲true,請求將被自動解析身體給你的對象JSON選項。您正在重新解析身體這一行:

var info = JSON.parse(body) 

當您嘗試解析一個對象,你會得到消息:

$ node 
> var t = {}; 
> JSON.parse(t); 
SyntaxError: Unexpected token o 
+0

謝謝。它怎麼沒有說'意外的令牌b'(body)而不是意外的令牌o? – dman

+2

因爲body是一個包含對象的變量。它試圖解析body.toString(),它是'[object Object]'。 –

+0

試試這個:https://www.npmjs.com/package/idempotent-json,如果它們已經被解析過,它不會重新解析對象 –

0
var request = require('request'); 
function updateClient(postData){ 
      var clientServerOptions = { 
       uri: 'http://'+clientHost+''+clientContext, 
       body: JSON.stringify(postData), 
       method: 'PUT', 
       headers: { 
        'Content-Type': 'application/json' 
       } 
      } 
      request(clientServerOptions, function (error, response) { 
       console.log(error,response.body); 
       return; 
      }); 
     } 

在客戶端side.And,

var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json()) 

var port = 9000; 

app.put('/sample/put/data', function(req, res) { 
    console.log('receiving data ...'); 
    console.log('body is ',req.body); 
    res.send(req.body); 
}); 

// start the server 
app.listen(port); 
console.log('Server started! At http://localhost:' + port); 

在服務器端。