vue配置代理解决跨域请求问题

2022-09-18 13:56:22

        http协议,请求地址,端口号,三者中有一种不同就会出现跨域请求的问题。可以通过配置代理服务器实现跨域请求;

        本次问题的具体场景如下,本人使用的vue版本为v2.9.6,后期配置主要修改config文件夹下的index.js。

二、具体应用场景

前端vue地址:

http://localhost:8080

后端数据请求地址:

http://localhost:8083/lytest/employee/getEmployeeList

axios:axios直接写跨域请求地址,会报CORS错误(请求成功,但是前端浏览器报异常,数据取不到)

this.$axios.get('http://localhost:8083/lytest/employee/getEmployeeList').then(res => {
        ......
      }).catch(err => {
        ......
      })

三、解决方案

        vue配置代理,具体操作步骤和说明如下。

1、具体步骤

1)修改项目下config/index.js文件,修改dev中的proxyTable配置。如果请求ip地址前后不同,最好写明请求后ip地址。如ip地址为xxx.xxx.x.xx,端口为8082,则target为http://xxx.xxx.x.xx:8082

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/lytest':{         //这里最好有一个 /
        target:'http://localhost:8083',  //后台接口域名
        changeOrigin:true,    //是否跨域
        ws:true,             //如果要代理 websockets,配置这个参数
        secure:false,       // 如果是https接口,需要配置这个参数
        pathRewrite:{       //重写请求路径
          '' : '' 
        }
      }
    }
    ......
}

2)修改axios请求url地址,要以 /lytest开头:

this.$axios.get('/lytest/employee/getEmployeeList').then(res => {
        ......
      }).catch(err => {
        ......
      })

2、以上图中的请求为例,进行说明:

1)原请求地址:/lytest/employee/getEmployeeList

2)node服务器遇到 以'/lytest'开头的请求,将 target 字段加上,请求地址变为:

http://localhost:8083/lytest/employee/getEmployeeList

3)pathRewrite 未配置路径重写,则最后的请求地址即为target加上后的地址

4)配置pathRewrite

(1)将开头的/lytest替换为空

pathRewrite:{
    '^/lytest' : '' 
}

(2)替换后,最后的请求地址如下。可用于最后请求没有/lytest 的情况下

http://localhost:8083/employee/getEmployeeList

5)重启vue项目

npm run dev 或  npm run serve

6)其他说明

        前端看到的请求地址是http://localhost:8080/lytest/employee/getEmployeeList,看起来没有代理,但是实际请求的时候已经代理了;可配置多代理。

推荐阅读:

vue设置代理 - 简书

Vue 解决跨域问题_南独酌酒nvn的博客-CSDN博客_vue的跨域怎么解决

vue 项目如何配置多个 proxy 代理_べJL的博客-CSDN博客_vue 多代理

  • 作者:Yanxigul
  • 原文链接:https://blog.csdn.net/qq_42077324/article/details/124130987
    更新时间:2022-09-18 13:56:22