cors在nginx,sails和socket Io中发行

时间:2018-03-12 15:57:02

标签: node.js nginx socket.io sails.js

我正在使用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'时,它不会#&# 39;工作。

我的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/;
}

我得到的错误如下所示

  

http://127.0.0.1/socket.io/?__sails_io_sdk_version=0.13.8&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=M8UlgQT 404(未找到)

非常感谢任何指针/帮助!

1 个答案:

答案 0 :(得分:0)

您的客户端应用程序在localhost:8080上运行,因此请将路径设置为&#39; / node&#39;将实际请求localhost:8080 / node并且找不到任何内容,因为您的API服务器在端口3000上运行,而不是在端口8080上运行。但是,当您指定localhost:3000时,这就是您的服务器所在的位置并且它正在运行。所以你应该添加

listen 8080;

到你的nginx配置,以拦截localhost:8080 / node请求,然后将重定向到localhost:3000。换句话说,你的nginx无效,因为它不会在正确的端口上监听。

但是,如果你这样做,可能你的jenkins服务器不起作用。所以我建议你在你的nginx中进行两个配置 - 两个都必须监听端口80,但是location /必须重定向到localhost:8080,而location / node必须重定向到localhost:3000。那么你的代码应该可以工作。