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
分类:
Vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.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 问题