关于配置vue的代理服务器新增两点建议

  1. 普通的http或者https请求。
    满足在vue.config.js配置一个普通的代理然后在使用该代理时可以不用写全完整的uri。而只用写具体的访问地址
    如下
    1
    2
    3
    4
    5
    6
    7
    8
    devServer:{
    proxy:{
    '/api/':{
    target:'http://localhost:9090/',
    pathRewrite:{'^/api':""},
    ws:false
    }
    }
    通过axios向后端发送请求时
    1
    2
    3
    4
    5
    6
    7
    this.axios({
    url:'/api/login',
    method:'get',
    params:{
    username:this.username
    }
    }).then
    只写具体的请求路径即可完成代理的转发。
  2. 通过WebSocket来完成转发时
    首先,他的代理必须打开ws,也就是将http协议升级为ws协议
    也是在vue.config.js中配置
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    devServer:{
    proxy:{
    '/ws/':{
    target: 'ws://localhost:9090/',
    pathRewrite: {
    '^/ws/': '/'
    },
    ws: true
    }

    }
    }
    此时与访问http请求不同的是,他在具体环节向后端发送ws链接请求时,必须把完整的访问地址写全,否则他将会被导向到http代理
    1
    this.socket = new WebSocket("ws://"+window.location.host +"/ws/chat/" + this.username)
    如上。