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?

1

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this and it gives the response: You must be authenticated to access this URL.
If the service is secured, you need to authenticate, it is clear in response.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.