目前,我在客户端和服务器上使用内置的 Meteor http 方法(请参阅 http://docs.meteor.com/#http )来发出 http 调用。
但是,我遇到两个问题:
- 可以取消请求吗?
- 是否可以有多个共享相同 key 的查询参数?
这些只是 Meteor 的限制,还是有办法使用 Meteor 让两者同时工作?
我知道我可以在客户端使用jquery,并且必须有一个支持两者的服务器端解决方案,但我更喜欢在这里坚持使用meteor代码。
最佳答案
"is it possible to cancel a request?"
HTTP.call()
似乎没有返回一个我们可以调用诸如 stop()
方法之类的对象。也许解决方案是阻止基于 Session
变量执行回调?
HTTP.call("GET", url, function(error, result) {
if (!Session.get("stopHTTP")) {
// Callback code here
}
});
然后,当您想要取消请求时,请执行以下操作:
Session.set("stopHTTP", true);
在服务器上,您可以使用 environment variable 而不是 Session
?
请注意,HTTP.call()
选项对象确实接受 timeout
键,因此如果您只是担心请求永远不会超时,您可以设置这是你想要的任何毫秒整数。
"is it possible to have multiple query parameters which share the same key?"
是的,这似乎是可能的。这是我使用的一个简单测试:
meteor 代码:
HTTP.call("GET", "http://localhost:1337", {
query: "id=foo&id=bar"
}, function(error, result) {
// ...
});
单独的 Node.js 服务器:(只是 Node.js 主页上的基本示例,使用 console.log
行输出带有查询字符串的请求 URL)
var http = require('http');
http.createServer(function(req, res) {
console.log(req.url); // Here I log the request URL, with the query string
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
当 Meteor 服务器运行时,Node.js 服务器记录:
/?id=foo&id=bar
当然,这仅适用于 GET URL 查询参数。如果您需要对 POST 参数执行此操作,也许您可以使用 EJSON.stringify
将单独的值存储为序列化数组字符串?
关于http - Meteor http 调用限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20847311/