2

I have a node.js application and I want to call a REST api by using http.request. This is my code:

http = require("http");

const options = {
        host: localhost,
        port: 8103,
        path: "/rest/getUser?userId=12345",
        method: "GET"
    };

http.request(options, function(res) {
   res.setEncoding('utf8');
   res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
      resolve(JSON.parse(chunk));
   });
}).end();

The above code works fine, but I don't want to include the request parameter ?userId=12345 in the path. The path should be: /rest/getUser. How do I set the request parameter with http.request?

M. Henrikh
  • 71
  • 1
  • 5
  • Possible duplicate of [node.js http 'get' request with query string parameters](https://stackoverflow.com/questions/16903476/node-js-http-get-request-with-query-string-parameters) – vapurrmaid Apr 11 '18 at 08:59

1 Answers1

3

You can use request package, which has more features, instead of built in http client.

var request = require('request');

var url = 'http://localhost:8103/rest/getUser/';

var paramsObject = { userId:12345 };

request({url:url, qs:paramsObject}, function(err, response, body) {
  if(err) { console.log(err); return; }
  console.log("Response: " + response.statusCode);
});
Areca
  • 1,292
  • 4
  • 11
  • 21