node.js http set request parameters

半腔热情 提交于 2021-01-28 01:59:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!