我正在使用Node.js和请求模块。我正在尝试发布请求api(restfull),但它没有正确发送请求。我可以在curl和python的请求模块中工作,但不能在node.js请求模块中工作:
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)
答案 0 :(得分:8)
将json选项设置为true,请求会自动将主体解析为对象。您正在使用以下行重新解析正文:
var info = JSON.parse(body)
当您尝试解析对象时,您会收到该消息:
$ node
> var t = {};
> JSON.parse(t);
SyntaxError: Unexpected token o
答案 1 :(得分:2)
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;
});
}
在客户端。然后,
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);
在服务器端。