我的应用程序 (http://localhost:8099
) 正在对我想要代理的 https://api.parse.com/
执行一些 CORS 请求我的本地 api http://localhost:8077
用于测试目的。这可以通过 grunt-connect-proxy
实现吗?
这是我的 grunt-connect-proxy 配置,它没有像我预期的那样工作。
connect: {
dev: {
options: {
port: 8099,
hostname: 'localhost',
base: 'build/',
livereload: false,
keepalive: true,
middleware: function (connect, options) {
var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
return [
// Include the proxy first
proxy,
// Serve static files.
connect.static('build/')
];
}
}
},
proxies: [
{
context: ['api/'], //same domain api requests, proxy works fine!
host: 'localhost',
port: 8077
},
{
context: ['api.parse.com/'], //cors, proxy is not working
host: 'localhost',
port: 8077,
changeOrigin: true
}]
}
→ grunt serve
Proxy created for: api/ to localhost:8077
Proxy created for: api.parse.com/ to localhost:8077
因此,基本上代理适用于 api/
请求(同一域),但对于 api.parse.com/
的 cors 请求则完全被忽略。想法?
最佳答案
当您向 api.parse.com
发出请求时,浏览器将连接到实际的 parse.com 服务器。 grunt-connect-proxy 只有在向应用程序服务器发出请求时才会出现,在您的例子中是 localhost:8099 。
对于您的应用程序(甚至是 localhost:8077),其他所有其他 localhost:8099 都是远程/跨域的,您可以在服务器端使用 grunt-connect-proxy 连接到这些服务器,而在客户端,您仍然可以请求到您自己的服务器。
使用上下文配置代理时连接到哪个服务器。
proxies: [
{
context: ['api/'],
host: 'localhost',
port: 8077
},
{
context: ['parse/'],
host: 'api.parse.com'
}]
所以,考虑到上面的配置
localhost:8099/api
--> 将到达 localhost:8077
和
localhost:8099/parse
--> 将转到 api.parse.com
关于javascript - 将带有 grunt 的 CORS 请求代理到本地主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29387904/