vue-cli中配置:

以下只适用于开发环境。

1/ 在devserver中配置如下:

  devServer: {
    host: '0.0.0.0',
    port: port,
    open: true,
    proxy: {
      // http代理
      [process.env.VUE_APP_BASE_API]: {
        target: `http://localhost:8080`,
        // secure: false, // 如果是https接口,需要配置这个参数为true
        changeOrigin: true, // 如果接口跨域,需要进行这个参数配置为true
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      },
       // websocket 代理
      [process.env.VUE_APP_BASE_WEBSOCKET]: {
        target: 'ws://localhost:8080',
        ws: true, //开启ws, 如果是http代理此处可以不用设置
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_WEBSOCKET]: ""
        }
      }
    },
  },

2/ .evn文件 

3/ 连接websocket 的url

// ··· ···
const URL = `ws://${location.host}/socket/websoc/warning/${userId}`
let websock = new WebSocket(URL)

加入前端服务是:localhost:8080, 只要前端访问 ws://localhost:8080/socket/xxx/xxx/**,都会被拦截,ws://localhost:8080/socket 会被替换为 target-> ws://localhost:8080, 然后拼接/xxx/xxx/**

需要注意几点:
     a、此处uri前面必须加ws://前缀

     b、uri的前缀后面必须是location.host,表示ws访问当前前端项目的地址,而不能只写代理的key值‘/socket’ 或其他地址端口

     c、在location.host后面紧跟的是代理key值,与env中定义的值一致‘/socket’

     d、地址中其他部分为后端api的uri

对应后台服务:

 

nginx中配置:

在实际开发中,如果前端开发使用代理,上线也需要代理的话,可在nginx中配置。

1/ 

server {
    listen       80;
    server_name  localhost;
    charset utf-8;
    // 前端静态服务器配置
    location / {
        root   D:\dist;
        try_files $uri $uri/ /index.html;
        index  index.html index.htm;
    }
    // http代理
    location /prod-api/ {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080/;
    }
    // websocket代理
    location /socket/ {  
        proxy_pass http://localhost:8080/; // 服务器地址
        proxy_http_version 1.1; // webscoket连接代理服务器必须使用http 1.1版本,默认
        proxy_set_header Upgrade $http_upgrade; // 连接升级
        proxy_set_header Connection "Upgrade"; // 要求客户端连接协议升级
        proxy_set_header X-Real-IP $remote_addr;
    }
}
Logo

前往低代码交流专区

更多推荐