在nodeJS中检索POST请求的JSON响应

时间:2017-10-26 23:08:27

标签: node.js rest

我正在向服务发送POST请求,它应该返回一个JSON作为响应。我看到POST是成功的,但我没有回复任何回复。我错过了什么?代码

var headers = {
    "Accept":"application/json",
    "Content-Type":"application/json",
    "Authorization": ("Basic " + new Buffer("admin:password").toString('base64'))

}




// Configure the request
var options = {
    url: 'myservice-url',
    method : 'POST',
    headers : headers
}


// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // Print out the response body
        var str = JSON.stringify(body, null, 2);
        console.log(str)

    }
})

1 个答案:

答案 0 :(得分:1)

首先,需要确认您是否正确安装了以下内容:

  

https://github.com/request/request

然后在你的文件中要求它:

var request = require('request');

    request.post({
        url: "",//your url
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        rejectUnauthorized: false,//add when working with https sites
        requestCert: false,//add when working with https sites
        agent: false,//add when working with https sites
        form: {
            whateverfieldnameyouwant: "whatevervalueyouwant"
        }
    },function (response, err, body){
        console.log('Body:',JSON.parse(body));
    }.bind(this));