node server.js
运行的整个服务器代码:var express = require('express');
var proxy = require('express-http-proxy');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);
server.use('/rest/api/2/search', proxy('restserver:8877'));
console.log("Server listening on localhost:8080");
当我在浏览器中访问restserver:8877/rest/api/2/search时,它会返回一堆json作为“默认”搜索结果。
在客户端,我使用iron-ajax来发出此请求:
<iron-ajax
id="getBugs"
url="/rest/api/2/search"
params=''
on-response="handleResponse"
debounce-duration="300">
</iron-ajax>
在脚本部分,我正在ready
函数中使用this.$.getBugs.generateRequest()
发送请求。所以我加载这个,期望请求不会被CORS阻止,因为...它被服务器代理了。然而,Chrome DevTools给了我以下内容:
XMLHttpRequest cannot load http://restserver:8877/secure/MyJiraHome.jspa. Redirect from 'http://restserver:8877/secure/MyJiraHome.jspa' to 'http://restserver:8877/secure/Dashboard.jspa' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
我不明白为什么它给我这些URL,因为我从未引用过它们,也不明白为什么由于跨域资源共享(CORS)而被阻止,因为它是从服务器发出的,而非客户端,这正是代理的全部意义。
cors
包,它不是你必须插入到express-http-proxy
中的东西。它是一个独立的中间件,允许你在目标服务器上接受来自经过筛选的主机列表的请求,例如app.use(cors(['http://localhost:8080', 'https://www.mywebsite.com']))
。如果你的问题仅仅是你的API服务器拒绝来自前端的请求,那么它可能会更有用和简单。 - geauser