如何使BrowserSync与nginx代理服务器配合工作?

(如果需要,请参阅my last question了解更多背景信息.)

我正在开发一个使用去耦前缀和后端的应用程序:

>后端是主要提供REST API的Rails应用程序(在localhost:3000上提供).
>前端是一个AngularJS应用程序,我正在使用Gulp和本地服务(使用BrowserSync)在localhost:3001上建立.

为了使两端互相交流,在尊重same-origin policy时,我配置了Nginx作为二者之间的代理,在localhost可用:3002.这是我的Nginx.conf:

worker_processes 1;

events {
  worker_connections 1024;
}

http {
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 65;

  server {
    listen 3002;
    root /;

    # Rails
    location ~ \.(json)${
      proxy_pass http://localhost:3000;
    }

    # AngularJS
    location / {
      proxy_pass http://localhost:3001;
    }
  }
}

基本上,对.json文件的任何请求,我正在发送到Rails服务器和任何其他请求(例如静态资产),我正在发送到browserSync服务器.

我的gulpfile.coffee的browserSync任务:

gulp.task 'browser-sync',->
  browserSync
    server:
      baseDir: './dist'
      directory: true
    port: 3001
    browser: 'google chrome'
    startPath: './index.html#/foo'

这一切基本上都是有效的,但有一些我要解决的注意事项:

>当我运行gulp任务时,根据上面的配置,browserSync加载一个Chrome选项卡在http:// localhost:3001 / index.html#/ foo.由于我使用的是Nginx代理,所以我需要端口为3002.有没有办法告诉browserSync,“在端口3001上运行,但从端口3002开始”?我尝试使用一个绝对路径的startPath,但它只期望一个相对的路径.
>每次browserSync启动时,我都会在控制台中看到一个(看起来很好)的JavaScript错误:WebSocket连接到’ws:// localhost:3002 / browser-sync / socket.io /?EIO = 3& transport = websocket& sid = m -JFr6algNjpVre3AACY’失败:WebSocket握手错误:意外的响应代码:400.不知道这是什么意思,但我的假设是,browserSync有点混淆了Nginx代理.

如何解决这些问题,使其无缝运行?

感谢任何输入!

最佳答案
要更好地控制如何打开页面,请使用opn而不是浏览器同步的机制.这样的东西(在JS中 – 对不起,我的咖啡脚本有点生锈):

browserSync({
    server: {
        // ...
    },open: false,port: 3001
},function (err,bs) {
    // bs.options.url contains the original url,so
    // replace the port with the correct one:
    var url = bs.options.urls.local.replace(':3001',':3002');
    require('opn')(url);
    console.log('Started browserSync on ' + url);
});

我不熟悉Nginx,但根据this page,第二个问题的解决方案可能如下所示:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

server {
    # ...

    # browserSync websocket
    location /browser-sync/socket.io/ {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
}

相关文章

Nginx (engine x) 是一个高性能的HTTP和反向代理服务,也是一...
本地项目配置 1 复制 luffy/settings/dev.py为prop.py 修改l...
nginx不仅可以隐藏版本信息,还支持自定义web服务器信息 先看...
一 、此次漏洞分析 1 nginx HTTP/2漏洞 [nginx-announce] ng...
###进入nginx 目录cd /usr/local/nginx###递归显示 2 级目录...
在cmd命令窗口输入下面命令进行查看 tasklist /fi "ima...