node.js http设置请求参数 [英] node.js http set request parameters
本文介绍了node.js http设置请求参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个node.js应用程序,我想使用>> http.request .这是我的代码:
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();
上面的代码工作正常,但是我不想在路径中包含请求参数?userId = 12345
.路径应为:/rest/getUser
.如何使用 http.request
设置请求参数?
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
?
推荐答案
您可以使用请求程序包,它具有更多功能,而不是内置在http客户端中.
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);
});
这篇关于node.js http设置请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文