Javascript 使用grunt将代理CORS请求发送到本地主机
我的应用程序(Javascript 使用grunt将代理CORS请求发送到本地主机,javascript,proxy,gruntjs,grunt-contrib-connect,grunt-connect-proxy,Javascript,Proxy,Gruntjs,Grunt Contrib Connect,Grunt Connect Proxy,我的应用程序(http://localhost:8099)正在向https://api.parse.com/我想代理到我的本地apihttp://localhost:8077用于测试目的。这可以通过grunt connect代理实现吗 下面是我的grunt connect代理配置,它的工作方式与我预期的不同 connect: { dev: { options: { port: 8099, hostname: 'localhost
http://localhost:8099
)正在向https://api.parse.com/
我想代理到我的本地apihttp://localhost:8077
用于测试目的。这可以通过grunt connect代理实现吗
下面是我的grunt connect代理配置,它的工作方式与我预期的不同
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代理只有在向应用程序服务器发出请求时才会出现,在您的例子中,应用程序服务器是localhost:8099
其他所有localhost:8099都是应用程序的远程/跨域(甚至localhost:8077),您可以在服务器端使用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
不是选项。host
表示要代理到的主机?您得到解决方案了吗?我也面临同样的问题issue@prudviraju最后,我拒绝了代理的想法,我只是在运行时根据节点更改api端点。\u env您可以共享更多信息吗please@prudviraju当然,解决方案很简单:apidendpoint=window.location.host=='localhost'?'http://localhost:8077' : 'https://api.parse.com
。