我是一名 ember 初学者,正在使用 ember-cli v0.0.47 并努力让 http-proxy 正常工作。
我正在尝试向远程 OGC CSW 服务器发出 ajax 请求。该请求是带有一些附加参数的普通 HTTP GET 请求,预期响应是 XML 文档。
由于我正在发出跨源请求,因此我决定使用服务器代理,以避免处理 CORS 内容。
我使用 ember-cli 生成代理配置:
ember-cli generate http-proxy geoland2 http://geoland2.meteo.pt
在我的 Controller 中,我定义了一个使用 jquery.ajax 与服务器通信的“搜索”操作:
export default Ember.Controller.extend({
actions: {
search: function() {
Ember.$.ajax({
url: 'geoland2/geonetwork/srv/eng/csw',
contentType: 'application/xml',
crossDomain: true,
xhrFields: {
withCredentials: true
},
dataType: 'xml',
data: {
service: 'CSW',
version: '2.0.2',
request: 'GetCapabilities'
},
}).then(
function(data) {
alert(data);
Ember.$('.results').html(data);
},
function(jqXHR, textStatus, errorThrown) {
Ember.$('.results').html(jqXHR.status + ' ' + errorThrown + ' - ' + jqXHR.responseText);
}
);
}
}
});
现在,当此操作被触发时,我希望调用
geoland2/geonetwork/srv/eng/csw
将由 ember-cli 的服务器代理并发送到
http://geoland2.meteo.pt/geonetwork/srv/eng/csw?service=CSW&version=2.0.2&request=GetCapabilitites
这种对应该发生的情况的假设正确吗?
实际上,我看到的是请求根本没有被代理。 ember 应用尝试联系
http://localhost:4200/geoland2/geonetwork/srv/eng/csw?service=CSW&version=2.0.2&request=GetCapabilitites
并且失败并出现 404 HTTP 错误,因为指定的资源显然不可用。
我编辑了自动生成的 server/proxies/geoland2.js
文件,方法是注释将 proxyPath
变量与 URL 的其余部分连接起来的行:
var proxyPath = '/geoland2';
module.exports = function(app) {
// For options, see:
// https://github.com/nodejitsu/node-http-proxy
var proxy = require('http-proxy').createProxyServer({});
var path = require('path');
app.use(proxyPath, function(req, res, next){
// include root path in proxied request
//req.url = path.join(proxyPath, req.url); // I commented this line
proxy.web(req, res, {target: 'http://geoland2.meteo.pt:80'});
});
};
这似乎适合我的用例,因为我的服务器端点位于
http://geoland2.meteo.pt/geonetwork/srv/eng/csw
不是
http://geoland2.meteo.pt/geoland2/geonetwork/srv/eng/csw
我相信即使这个更改可能是错误的,我也应该从原始服务器取回一些东西。
我是否仍然需要修复一些与 CORS 相关的问题才能使代理正常工作?或者也许还需要编辑一些文件才能正确设置 http 代理?
最佳答案
在当前版本的 ember cli 中,您可以使用指向外部服务器的代理选项来启动应用程序。
ember server --proxy http://externalserver.ccc/api/
关于jquery - ember-cli http 代理不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26456381/