Vue项目中proxyTable解决axios跨域问题

深碍√TFBOYSˉ_ 2023-05-22 06:54 99阅读 0赞

1.在Vue项目中config文件下的index.js添加proxyTable的代码

  1. dev: {
  2. // 静态资源文件夹
  3. assetsSubDirectory: 'static',
  4. // 发布路径
  5. assetsPublicPath: '/',
  6. // 代理配置表,在这里可以配置特定的请求代理到对应的API接口
  7. // 例如将'localhost:8080/api/xxx'代理到'http://xxxxxx.com/api/xxx'
  8. proxyTable: {
  9. '/api': {
  10. target: 'http://xxxxxx.com', // 接口的域名
  11. // secure: false, // 如果是https接口,需要配置这个参数
  12. changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
  13. pathRewrite: {
  14. '^/api': ''
  15. }
  16. }
  17. },

2.在需要请求接口的组件中填写axios请求接口的代码,需要在url的位置加/api路径,例如请求 /login时,url需要写成 /api/login,此时 /api代表http://xxxxxx.com

  1. // created:vue生命周期中的钩子函数,在这个时间点,data中的数据已经注入到响应式系统中
  2. created(){
  3. axios.get('/api/login'
  4. ).then(function(res){
  5. console.log(res.data);
  6. }).catch(function (error) {
  7. console.log(error);
  8. });
  9. }

注意: ‘/api’ 为匹配项,target 为被请求的地址,因为在 ajax 的 url 中加了前缀 ‘/api’,而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 ‘/api’ 转为 ‘/’。如果接口地址中就有 ‘/api’ 这种通用前缀(例如http://xxxxxx.com /api/login,),就可以把 pathRewrite 删掉或者写成 ‘^/api’: ‘/api’。

  1. proxyTable: {
  2. '/api': {
  3. target: 'http://xxxxxx.com', // 接口的域名
  4. // secure: false, // 如果是https接口,需要配置这个参数
  5. changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
  6. pathRewrite: {
  7. '^/api': '/api'
  8. }
  9. }
  10. },

若是定义的axios的baseURL请求接口时发生了跨域,请看《Vue项目中proxyTable解决axios的baseURL跨域问题》

发表评论

表情:
评论列表 (有 0 条评论,99人围观)

还没有评论,来说两句吧...

相关阅读