krishna
krishna

Reputation: 405

npm request.post giving error everytime but the same post works with JQuery

I am trying to make a post request from express js to an api, from serverside.

Here is the code for it

request.post({
                url: $url,
                crossDomain: true,
                data: {id : '392', sid: 'abc'}
                }, function(error, response, body){
                    console.log(response.statusCode);
                    console.log(body);
            });

this always returns with a response statusCode 500;

On the other hand, I tried the same post request from server side using Jquery.

Here is the code for it.

$.ajax({
    url: $url,
    crossDomain:true,
    data: {
        id : $id,
        sid: $sid
    },
    type: "POST",
    // dataType: "json",

    //on success
    success: function(response){
        //do something after something is received data
    },
    //on error
    error: function(jqXHR, exception){
        //bad request
        console.log(jqXHR.status);
        console.log(exception);
    }
});

The $url and all the other variables are same in both the cases. Though, I get proper response and status code 200 for the post I do with Jquery, unlike the one I do with npm request module.

Where am I going wrong?

Upvotes: 0

Views: 52

Answers (2)

peteb
peteb

Reputation: 19428

request and $.ajax don't have the same options when being called. You can send the request body using the body property in the options object passed. Additionally, there is the convenience boolean json to add the Content-Type:application/json header to the request, serialize the request body as JSON and to automatically parse the response body as JSON.

const request = require('request')

request({
  url: $url,
  method: 'POST',
  body: {id: '392', sid: 'abc'},
  json: true
}, (err, res, body) => {
  if (err) {
    // handle error
    console.log(err)
    return
  }

  // handle response
  console.log(response)      
})

Upvotes: 0

Pieter-Jan Beeckman
Pieter-Jan Beeckman

Reputation: 215

And what about this code?

I also don't seem to find any reference to the 'crossDomain' option in the request.js docs

var request = require('request');
request.post(
    {
        headers: {'content-type':'application/json'},
        url: $url,
        form: {id : '392', sid: 'abc'}
    },
    function(error, response, body){
        console.log(response.statusCode);
        console.log(body)
    }
);

Upvotes: 1

Related Questions