加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

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

发布时间:2020-12-13 21:28:35 所属栏目:Nginx 来源:网络整理
导读:(如果需要,请参阅my last question了解更多背景信息.) 我正在开发一个使用去耦前缀和后端的应用程序: 后端是主要提供REST API的Rails应用程序(在localhost:3000上提供). 前端是一个AngularJS应用程序,我正在使用Gulp和本地服务(使用BrowserSync)在localhos

(如果需要,请参阅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";
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读