前言:
本地項(xiàng)目在請求遠(yuǎn)端服務(wù)器接口時(shí),不可避免的會遇到跨域問題,即便是設(shè)置了Access-Control-Allow-Origin:* 泊交,在遇到登錄這些需要本地存入cookie的也會很頭痛儿奶,這里筆者介紹一個(gè)在vue-cli中配置代理來解決的辦法眷射。
在~/config/dev-server.js中 使用了非常強(qiáng)大的 http-proxy-middleware 包镇辉。更多高級用法,請查閱其文檔厅目。
用法:
比如我們要請求的遠(yuǎn)端服務(wù)器為:http://192.168.400:3000
proxyTable: {
'/api/': {
target: 'http://192.168.400:3000',
changeOrigin:true, //set the option changeOrigin to true for name-based virtual hosted sites
pathRewrite: {
'^/api': '/api'
}
},
},
- 通過設(shè)置changeOrigin:true 開啟代理
- pathRewrite 意為重寫路徑
示例:
比如要請求的接口為http://192.168.400:3000/api/main/getUserInfo.action
this.$http.post('/api/main/getUserInfo.action')
.then(res=>{
console.log(res)
})
后續(xù):
在實(shí)際工作中番枚,我們還需要做些其他的,比如在axios中配置baseUrl:
/**
* Created by Administrator on 2017/4/11.
*/
import axios from 'axios';
// 添加響應(yīng)攔截器
axios.interceptors.request.use(function (config) {
// 配置發(fā)送請求的信息
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, /*設(shè)置請求超時(shí)時(shí)間*/
baseURL:'http://192.168.400:3000',
});
// Alter defaults after instance has been created
http.defaults.headers.common['Authorization'] = '';
export default http;
/**導(dǎo)出http损敷,在mainjs中引用
import http from './config/axiosConfig';
Vue.prototype.$http = http;
**/