简体   繁体   中英

retrieve JSON response of a POST request in nodeJS

I am sending s POST request to a service and it is supposed to return a JSON in response. I see the POST is successful but I dont get anything in response back. What am I missing? Below code

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)

    }
})

First of all, need to confirm if you have properly installed the following:

https://github.com/request/request

Then require it in your file like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM