【发布时间】:2014-10-23 08:12:52
【问题描述】:
我在使用 nginx 和sails 时遇到了跨域配置问题。问题是
如果我让套接字通过http://domain-server.com/socket.io/ 正确连接
那么 RESTful 请求将失败。如果 RESTful 有效,则套接字不会。
设置
客户http://domain.com
服务器http://server-domain.com
客户端是一个使用"sails.io.js": "0.10.3" 和此配置io.sails.url = 'http://domain-server.com'; 的角度应用程序。
Server 是一个兼具 RESTful 请求和套接字功能的 Sails 应用程序。
Sails CORS 配置
module.exports.cors = {
allRoutes: true,
origin: 'http://domain.com',
credentials: true,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
headers: 'content-type,Access-Control-Allow-Origin'
};
Sails 套接字配置
module.exports.socket {
onConnect: function() {},
onDisconnect: function() {},
authorization: false,
'backwardsCompatibilityFor0.9SocketClients': false,
grant3rdPartyCookie: true,
origins: 'http://domain.com'
};
nginx 配置
注释掉的是我在 nginx 配置中摆弄但没有取得多大成功(也尝试了客户端地址而不是 *)。
server {
listen 80;
server_name domain-server.com;
#add_header Access-Control-Allow-Origin *;
location / {
# add_header Access-Control-Allow-Origin *;
proxy_pass http://localhost:1337;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
# proxy_set_header Access-Control-Allow-Origin *;
proxy_cache_bypass $http_upgrade;
}
}
进行 RESTful 调用的 angularjs 服务方法
function query(path, attributes) {
return $http({
url: domain + path,
params: attributes,
method: "GET",
widthCredentials: true
});
}
在角度配置函数中
$httpProvider.defaults.useXDomain = true;
这是当前配置,这是我正在体验的结果。
浏览器控制台输出
Resource interpreted as Script but transferred with MIME type text/html: "http://domain-server.com/__getcookie". - 好
|> - 好
\___/ sails.io.js:200
io.socket connected successfully.
XMLHttpRequest cannot load http://domain-server.com/login?password=test&username=test.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://domain.com' is therefore not allowed access. - 不好
更新
如果我直接使用sails lift 或node app.js 开始航行,似乎一切正常,但是当使用.conf 文件中的新贵脚本启动它时,会发生跨域问题。
新贵脚本
#!upstart
description "demo"
author "gillesc"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn
respawn limit 5 60
script
exec /usr/bin/node /var/www/apps/domain-server.com/app.js > /var/www/apps/domain-server.com/server.log 2>&1
end script
【问题讨论】:
-
这是在哪里托管的?某些云主机(如 OpenStack)似乎阻止发送 CORS 标头。
-
我可以让 CORS 为 RESTful 正常工作,只是当他们做 socket.io 方面的事情不再工作时。听起来某处发生了冲突。
-
如果您在浏览器中导航到
http://domain-server.com/login?password=test&username=test,您会得到什么?它是一个nginx错误页面吗?您是否正确地将请求从 nginx 反向代理到sails 应用程序?还是它们在不同的端口上? -
@david 我从 nginx 收到
Not Found,我认为 404 帆视图只是字符串404。 -
是的,听起来您正在从同一个端口为sails 应用程序和websocket 提供服务。要么将 websocket 切换到不同的端口,要么决定哪些 url 应该转到哪个并设置 nginx。
标签: angularjs nginx sails.js upstart sails.io.js