vue 使用 devServer 代理实现 Axios跨域请求

devServer  实现纯前端配置代理解决axios跨域 

注:devServer 只在 开发环境 有效   

如果实现 编译后跨域  可采用 nginx代理的方法 可参考:https://www.cnblogs.com/hailexuexi/p/14934166.html

一、在 vue.config.js 中  加入下面代码

复制代码
//-----------------------Axios跨域请求-----------------------------------------
  devServer:{
    port:4000,//vue网页访问的端口
    host:"127.0.0.1",//vue网页访问的地址
    https:false,
    open:false,
    proxy: {
        '/sina': {  //为用于替换的的标识字符串
            target: 'http://192.168.1.5',//Axios跨域请求的IP
            changeOrigin: true, 
            ws: true,
            pathRewrite: {
                '^/sina': '' //不用改
            }
        },
         
        '/phpUrl': {  //为用于替换的的标识字符串
          target: 'http://192.168.1.8:8080/VueApi',//Axios跨域请求的IP
          changeOrigin: true, 
          ws: true,
          pathRewrite: {
              '^/phpUrl': '' //不用改
          }
       }  
    }
}
复制代码

二、在请求中这样写

复制代码
    //获取users列表--------------Sina API--Axios跨域 Post请求----------
     this.$axios.get('/sina/api/users')
          .then(function (response) {
            //console.log(response);
            let { statusText, data } = response.data;//解析JSON
            //console.log(data);
             
      }.bind(this))
      .catch(function (error) {
        console.log(error);
      });
复制代码

目的:

将   this.$axios.get('/sina/api/users')  中的  /sina   变成  http://192.168.1.5

现实   this.$axios.get(' http://192.168.1.5/api/users')  

 

感谢原作者:wh_xmy

https://blog.csdn.net/wh_xmy/article/details/87705840

 

posted @   海乐学习  阅读(54)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2017-06-26 easyui-linkbutton 设置和获取text文本
2013-06-26 CSC时无法找到C:\Program Files\Microsoft SDKs\Windows\v6.0A\lib
2011-06-26 vs2008 C++ 没有找到MSVCR90D.dll 问题
点击右上角即可分享
微信分享提示