关于vue2用vue-cli搭建环境后域名代理的http-proxy-middleware解决api接口跨域问题
2024-10-19 11:42:43
在vue中用http-proxy-middleware来进行接口代理,比如:本地运行环境为http://localhost:8080但真实访问的api为 http://www.baidu.com这时我们就需要把http://www.baidu.com代理到api接口上
在build下的 dev-server.js 中我们需要对下面代码进行修改
var proxyMiddleware = require('http-proxy-middleware');
var proxyMiddleware = require('http-proxy-middleware') var server = express() server.middleware = [
proxyMiddleware(['/mobile'], {target: 'http://baidu.com', changeOrigin: true}),
proxyMiddleware(['/school'], {target: 'http://baidu.com', changeOrigin: true}),
proxyMiddleware(['/api/track'], {target: 'http://baidu.com', changeOrigin: true}),
proxyMiddleware(['/manage/integral'], {target: 'http://baidu.com', changeOrigin: true}),
]; server.use(server.middleware);
这里需要注意需要把接口调用的开始部分分别写在 proxyMiddleware中 如 /mobile是代表你访问的接口为 http://baidu.com/mobile/ 开头的所有接口 相当于http://baidu.com/mobile/*
在调用的时候我们用 vue-resource,在main.js中引入
vue-resource 的安装方式: npm install --save-dev vue-resource
import VueResource from 'vue-resource' Vue.use(VueResource)
在页面中具体调用为
this.$http.get('/mobile/api/h5/', {params: {name:1,type:2}}).then((response) => {
response = response.body;
if (response.errno === 0) {
this.goods = response.data;
}
});
到这里我们就完成了vue的代码域名代理,如有错误,或错别字欢迎大家留言指正!
最新文章
- zepto区别于jquery获取select表单选中的值
- php+mysql+Apache环境搭建
- C++中int,float,string,char*的转换(待续)
- centos 终端 字体颜色
- 安卓中級教程(2):@InjectView中的對象inject
- BZOJ-1196 公路修建问题 最小生成树Kruskal+(二分??)
- PHP iconv函数字符串转码导致截断问题
- 修改shell 将当前shell(默认是bash B SHELL )改为csh C SHELL
- js时间戳转换时间格式
- Linux入门(13)——Ubuntu16.04下将图片和pdf互转
- Zookeeper 笔记-应用场景
- Java课程课后作业190309之连续最大子数组
- codecademy课程笔记——JavaScript Promise
- 队列->;队列的表示和实现
- 浏览器下载Excel,直接打开显示乱码...
- catalan 递推
- DocumentFragment类型
- min cost max flow算法示例
- POJ 3468 A Simple Problem with Integers(线段树&;区间更新)题解
- 关于json_encode()的使用注意
热门文章
- Alamofire源码导读三:返回的处理逻辑
- docker微服务部署之:七、Rancher进行微服务扩容和缩容
- Java之集合(十三)WeakHashMap
- Linux的文件的打包(tar方法)
- Ubuntukylin-14.04-desktop(带分区)安装步骤详解
- 解决chrome,下载在文件夹中显示,调用错误的关联程序
- web前端html快速入门
- linux安装tmux
- 【广州.NET社区推荐】.NETCore 平台上的日志集成组件 TomatoLog
- java的PreparedStatement中使用like时的问题