您的位置:首页 > 产品设计 > UI/UE

Vuejs2.0 利用proxyTable实现跨域请求

2017-12-18 13:56 363 查看
前言:

本地项目在请求远端服务器接口时,不可避免的会遇到跨域问题,即便是设置了Access-Control-Allow-Origin:* ,在遇到登录这些需要本地存入cookie的也会很头痛,这里笔者介绍一个在vue-cli中配置代理来解决的办法。

在~/config/dev-server.js中 使用了非常强大的http-proxy-middleware 包。更多高级用法,请查阅其文档。

用法:

比如我们要请求跨域的端口为:http://127.0.0.1:3000

proxyTable: {
'/data_add/': {
target: 'http://127.0.0.1:3000',
changeOrigin:true,
pathRewrite: {
'^/data_add': '/data_add'
}
},
},


1.通过设置changeOrigin:true 开启代理

2.pathRewrite 意为重写路径

示例:

比如要请求的接口为http://127.0.0.1:3000/data_add

this.$http.post('/data_add')
.then(res=>{
console.log(res)
})


后续:

在实际工作中,我们还需要做些其他的,比如在axios中配置baseUrl:

/**
* Created by Administrator on 2017/12/18.
*/
import axios from 'axios';

// 添加响应拦截器
axios.interceptors.request.use(function (config) {
// 配置发送请求的信息

return config;
}, function (error) {
return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
// 配置请求回来的信息

return response;
}, function (error) {
return Promise.reject(error);
});

var http = axios.create({
timeout: 8000, /*设置请求超时时间*/
baseURL:'http://127.0.0.1:3000',

});

// Alter defaults after instance has been created
http.defaults.headers.common['Authorization'] = '';

export default http;

/**导出http,在mainjs中引用
import http from './config/axiosConfig';
Vue.prototype.$http = http;
**/


以上就是本文的全部内容,希望对大家的学习有所帮助
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: