我正在尝试从Node.js应用程序向Rails服务器发送GET请求。目前,我使用的request
模块如下所示:
var request = require("request");
var url = 'www.example.com'
function sendRequest(url){
string = 'http://localhost:3000/my-api-controller?url=' + url;
request.get(string, function(error, response, body){
console.log(body);
});
}
这是可行的。但我想要的不是为get
请求构建string
,而是将请求的参数作为javascript对象传递(以类似于jQuery的方式)。request
模块的wiki页面上有一个one example,它使用的正是这种语法:
request.get('http://some.server.com/', {
'auth': {
'user': 'username',
'pass': 'password',
'sendImmediately': false
}
});
但是,当我尝试将此语法应用于我的目的时,如下所示:
function sendRequest(url){
request.get('http://localhost:3000/my-api-controller', {url: url}, function(error, response, body){
console.log(body);
});
}
未发送url
参数。
所以我的问题是,是我做错了什么,还是request
模块不支持将get
请求的参数作为javascript对象传递?如果没有,你能推荐一个方便的Node模块吗?
发布于 2015-04-14 08:53:57
您在request
模块中指向的"HTTP Authentication“示例不会构建查询字符串,它会根据特定的选项添加身份验证头。该页面的another part描述了您想要的内容:
request.get({url: "http://localhost:3000/my-api-controller",
qs: {url: url}},
function(error, response, body){
console.log(body);
});
差不多吧。正如注释中提到的,这反过来使用querystring
模块来构建查询字符串。
发布于 2015-04-14 08:54:29
提供给request()
或其convenience methods的对象不仅仅是用于数据参数的。
要提供在查询字符串中发送的{ url: url }
,您需要使用qs
选项。
request.get('http://localhost:3000/my-api-controller', {
qs: { url: url }
}, function(error, response, body){
// ...
});
https://stackoverflow.com/questions/29617328
复制相似问题