Node.js Request Module…sending json in body for api request with put

来源:互联网 发布:淘宝上买什么东西好 编辑:程序博客网 时间:2024/05/16 16:22

http://stackoverflow.com/questions/21359877/node-js-request-module-sending-json-in-body-for-api-request-with-put

用Node.js的Request模块发送post请求,request body为JSON对象,需要设置json: true

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);    }}

其返回的response body也是JSON对象,所以不需JSON.parse(body),否则会报错

With the json option set to true, request is automatically parsing the body for you to an object. You are re-parsing the body with this line:

var info = JSON.parse(body)

When you try to parse an object, you get that message:

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


0 0