我正在尝试使用Meteor的(v1.0)HTTP.call
方法与基于Python的服务器进行通信,该服务器仅接受标头中的application/json
内容类型,但我无法正确设置HTTP标头从客户端调用API URL时的Meteor。
使用这样的代码段,我从Python服务器收到415 (Unsupported Media Type)
错误:
if (Meteor.isClient) {
Template.testing.events({
'click button': function(event, tpl) {
event.preventDefault();
var method = 'GET';
var url = 'http://localhost:6543/test';
var options = {
headers: {'Content-Type': 'application/json'}
}
HTTP.call(method, url, options, function(error, result) {
if (error) {
console.log('ERRR');
console.log(error);
} else
console.log('RESULT');
console.log(result);
});
}
});
}
但是,如果我在Meteor中从服务器端调用相同的URL,如下所示:
if (Meteor.isClient) {
Template.testing.events({
'click button': function(event, tpl) {
event.preventDefault();
var method = 'GET';
var url = 'http://localhost:6543/test';
var options = {
headers: {'Content-Type': 'application/json'}
}
Meteor.call('APICall', method, url, options, function (error, result) {
if (error) {
console.log('CLIENT ERRR');
console.log(error);
} else {
console.log('CLIENT RESULT');
console.log(result);
}
});
}
});
}
if (Meteor.isServer) {
Meteor.methods({
APICall: function (method, url, options) {
HTTP.call(method, url, options, function(error, result) {
if (error) {
console.log('SERVER ERRR');
console.log(error);
} else
console.log('SERVER RESULT');
console.log(result);
});
}
});
}
我从服务器得到了正确的答复。
在Python方面,我为所有可能的请求启用了CORS起源(例如cors_origins=('*')
)。
那么......可以在客户端设置标头,还是应该总是从服务器端调用此服务?
答案 0 :(得分:0)
我在客户端也没有取得任何成功,但它应该是。查看meteor HTTP包的HTTP.call客户端部分:
https://github.com/meteor/meteor/blob/devel/packages/http/httpcall_client.js
大多数情况下,它在客户端使用浏览器XHR对象,这可能导致许多问题,如不兼容性和内容。您甚至可以在其中一个代码注释(约line 136)
上看到引用的问题 And when you check out the server implementation您可以看到它使用request
库(来自connect
),在我的书中,它非常可靠,您可以在所有用户中生成统一的结果(而不是围绕浏览器差异跳舞。)
我的选择和推荐显然是服务器端调用。不仅因为它的工作原理而且它是可靠的,而且您也可以“更安全”,因为您不必将更多系统内部工作暴露给客户端/最终用户。谁知道?也许你在基于Python的服务器上运行的API上有敏感数据。