【发布时间】:2018-08-20 17:24:33
【问题描述】:
我有一个 Sails 应用程序,我在其中使用套接字 IO 通知客户端某些事件。我将 nginx 作为代理服务器,因此每当请求具有 /node/anything 时,它都会重定向到 localhost:3000/anything。
将以下代码视为控制器内的代码,它只是发出/爆炸套接字事件
getData: async (req, res) => {
let jobName = req.params.jobName || '';
if(!jobName || !jobName.trim()) {
return res.negotiate({ error: "Please provide a job name" });
}
try {
let builds = await getAllData(jobName);
let result = {
total : builds.length || 0,
items : builds
};
// This is the part that emits an event
sails.sockets.blast('message', { message: 'Server returns all the builds' });
return res.json(result);
} catch(error) {
let custErrMsg = `Request Parameter: Job Name = ${ req.param('jobName') }`;
let errMsg = ErrorService.getErrMsg(error, custErrMsg);
return res.negotiate({ error: errMsg });
}
}
现在客户端甚至可以监听。
/node is the name of upstream set in the nginx config please see below. The script is being loaded inside the index.html from the server(API application). Both the client and API runs on same domain (127.0.0.1) but API runs on 3000 port and client side app runs on 8080 where Jenkins server is running. And Index.html is served from /var/lib/userContent/jenkins/clientApp directory
//index.html
<!DOCTYPE html>
<html>
<head>
<meta content="text/html" charset="utf-8">
<title>My Jobs</title>
<script type="text/javascript" src="/node/js/dependencies/sails.io.js"></script>
<script type="text/javascript">
io.sails.url = '//localhost:3000'; //works
<!-- io.sails.url = '/node; --> // doesn't
</script>
</head>
<body>
Hello World
</body>
</html>
脚本标签引用了驻留在我的 API 应用程序中的 socket.io 文件所以io.sails.url = '//localhost:3000' 工作正常,因为服务器在 3000 上运行,但是当我将其更改为 io.sails.url = '/node' 时它不起作用。
我的 nginx.conf 中有以下配置
upstream node {
server localhost:3000;
}
location /node/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://node/;
}
我得到的错误如下所示
非常感谢任何指针/帮助!
【问题讨论】:
标签: node.js nginx socket.io sails.js