当前位置:
首页
文章
前端
详情

webpack proxy代理

在配置proxy的时候,//xxx 最好不要同时存在,因为 / 会匹配所有,以至不同的服务器都会走 /,从而导致报错

webpack proxy配置文档:https://www.webpackjs.com/configuration/dev-server/#devserverproxy

api接口代理

proxy: {
  '/api': {
      target: 'http://192.168.xx.xx:8082',
      ws: false,
      changeOrigin: true,
      pathRewrite: {
        '^/api': '/api'
      }
  }
}

请求示例:

import axios from 'axios'

axios.get('/api/user/list', {params: {page: 1}})

// 或
axios.get('http://localhost/api/user/list', {params: {page: 1}})

// 或
axios.get('http://127.0.0.1/api/user/list', {params: {page: 1}})

websocket代理

proxy: {
  '/ws': {
      target: 'http://192.168.xx.xx:8082',
      ws: true,
      changeOrigin: true,
      pathRewrite: {
        '^/ws': '/'
      }
  }
}

连接示例:

let ws = new WebSocket("ws://localhost:8080/ws");
// 或 
// let ws = new WebSocket(`${location.protocol.replace(/http/, 'ws')}//${location.host}/ws`);
ws.addEventListener("open", function(event) {
  console.log("WebSocket连接已建立");
});
ws.onmessage = function(event) {
  console.log("收到消息:" + event.data);
};
ws.send("Hello, WebSocket!");
ws.close();

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。