Search code examples
javascriptnode.jsexpresshttprequest

Translate curl to node request


I have a curl that looks like this:

curl -X "POST" "https://theEndpoint.com" \
-H "Authorization: Basic theEncodedUserName/Password" \
-H "Content-Type: application/json" \
-d "{\"GETRSDATA_Input\":{\"@xmlns\":\"http://theEndpoint.com\",\"RESTHeader\":{\"@xmlns\":\"http://theEndpoint.com/header\"},\"InputParameters\":{\"P_CHANGESINCE_DATE\":\"0460070398\"}}}"

I'm using the request module in my express app like this:

var options = {
  method: 'POST',
  url: 'https://theEndpoint.com',
  headers: {
      'Authorization': 'Basic theEncodedUserName/Password',
      'Content-Type': 'application/json',
  },
  multipart: [{
      'content-type': 'application/json',
      body: JSON.stringify({"GETRSDATA_Input":{"@xmlns":"http://theEndpoint.com","RESTHeader":{"@xmlns":"http://theEndpoint.com/header"},"InputParameters":{"P_CHANGESINCE_DATE":"0460070398"}}})
}],

I have a callback function to handle the response and I run it with:

request(options, callback);

Does that look right? I don't believe I'm setting up the request properly.


Solution

  • You're pretty close to being correct but not quite, there are a few things about your request options that need to change.

    If you're going to be passing JSON in the request you don't need to set the Content-Type header. request provides the flag json which is a boolean value, if true then Content-Type will be set to application/json and the body will be properly stringified, the response will also be properly parsed to JSON.

    Additionally, your request body shouldn't be passed in the multipart attribute because you're not making a multipart request. You should be using the body attribute.

    I also see that your request body is already stringified based on what you supplied in the question. You don't need to stringify it beforehand as I stated above request will take of that for you.

    When doing Basic Auth, you can use the auth property on the request. For more info on the auth property see the request auth docs

    var reqBody = JSON.parse("{\"GETRSDATA_Input\":{\"@xmlns\":\"http://theEndpoint.com\",\"RESTHeader\":{\"@xmlns\":\"http://theEndpoint.com/header\"},\"InputParameters\":{\"P_CHANGESINCE_DATE\":\"0460070398\"}}}");
    
    var options = {
      method: 'POST',
      url: 'https://theEndpoint.com',
      auth: {
        user: YourUsername,
        password: YourPassword,
        sendImmediately: true
      },
      body: reqBody,
      json: true
    };
    
    request(options, function(err, res, body) {
        // If an error occurred return the error.
        if (err) return err;
    
        // No error occurred return the full reponse
        return res;
    });