首页 > 其他分享 >Vue-Cli devServer.proxy 配置代理服务,解决跨域请求报错的问题

Vue-Cli devServer.proxy 配置代理服务,解决跨域请求报错的问题

时间:2023-03-17 22:11:23浏览次数:36  
标签:Vue http 代理服务 代理 5000 报错 student localhost 请求

如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。

方法一

在vue.config.js中添加如下配置:

devServer:{
  proxy:"http://localhost:5000"  
}

说明:

1、优点:配置简单,请求资源时直接发给前端(8080)即可

2、缺点:不能配置多个代理,不可灵活的控制请求是否走代理

3、工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)

例如:http://localhost:8080/student

若前端public目录下有student,会优先获取public下的student

若前端public目录下没有student,才会请求 http://localhost:5000/student

 

方法二

编写vue.config.js 配置具体代理规则:

  //使用时是: http://localhost:8080/api1/student   //会转成:http://localhost:5000/api1/student
modul.exports={
  devServer:{
        proxy:{
           '/api1':{ //匹配所有以 ‘/api1’开头的请求路径
                target:'http://localhost:5000', //代理目标的基础路径
                changeorigin:true,
                pathRewrite:{'^/api1':''}//重定向
                 //将原来的 http://localhost:5000/api/student                  //重定向为 http://localhost:5000/student
            },
           '/api2':{ //匹配所有以 ‘/api2’开头的请求路径
                target:'http://localhost:5001', //代理目标的基础路径
                changeorigin:true,
                pathRewrite:{'^/api2':''}
            },
        }               
    }  
}            

changOrigin设置为true时,服务器收到的请求头中的host为 localhost:5000

changOrigin设置为false时,服务器收到的请求头中的host为 localhost:8080

changeOrigin默认值为true

说明:

1、优点:可以配置多个代理,且可以灵活的控制请求是否走代理

2、缺点:配置略微繁琐,请求资源时必须加前缀

 

标签:Vue,http,代理服务,代理,5000,报错,student,localhost,请求
From: https://www.cnblogs.com/technicist/p/17228380.html

相关文章