问题
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:
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);
});
来源:https://stackoverflow.com/questions/49770523/node-js-http-set-request-parameters