Retrieve response of PUT request

时间:2016-08-31 17:13:38

标签: node.js

I am using NodeJS to send a PUT request to a private API that I have access to. When using curl the API sends back JSON and everything works great, but when using NodeJS it isn't sending back anything. I am very new to this and I know my code isn't the best, but it works (other than this one problem). I am wondering how to display the JSON that I should be retrieving back from the the PUT request in the terminal.

NodeJS Server Code:

app.post('/myaction', function(req, res) {
    var data = req.body.service;
    var data1 = req.body.serviceId;
    console.log(data);
    console.log(data1);
    res.sendFile(__dirname + '/services.html');
    myURL = 'http://privateAPI.com/service_instance/' + data1;
    console.log(myURL)
request({
    method: 'PUT',
    uri: myURL,
    multipart: [{
       'content-type':'application/json',
        body: data 
    }]
    }, function(error, request, body){
    })
});

When I console.log(body) I get the HTML of the API. When I console.log(request) I get the JSON I am sending to the API. When I console.log(error) I get Null.

Links I've read but didn't help: How to retrieve POST query parameters?
How to retrieve POST query parameters?

1 个答案:

答案 0 :(得分:0)

Actually you don't need to use multipart.

But the problem is that you need to set the content type you expected from the API.

request({
    method: 'PUT',
    uri: myURL,
    headers: {
      'accept': 'application/json',
      'content-type': 'application/json'
    },
    multipart: [{
       'content-type':'application/json',
        body: data 
    }]
    }, function(error, response, body){
       console.log(response);
    })

Without multipart

request({
    method: 'PUT',
    uri: myURL,
    headers: {
      'accept': 'application/json',
      'content-type': 'application/json'
    },
    body: data,
    json: true
    }, function(error, response, body){
       console.log(response);
    })