vue跨域解決方法
使用axios請求
第一步驟
在vue.config.js 文件中 module.exports = { } 中添加
devServer: {
proxy: {
'/profile': { //指定 路徑 要 跨域請求地址
// 在本地會創(chuàng)建一個虛擬服務(wù)端,然后發(fā)送請求的數(shù)據(jù)耘拇,并同時接收請求的數(shù)據(jù)撵颊,這樣服務(wù)端和服務(wù)端進行數(shù)據(jù)的交互就不會有跨域問題
// 將/api開頭的url轉(zhuǎn)發(fā)到target上。
target: 'https://sso.www.eee.cn/profile',//跨域請求地址
changeOrigin: true, //虛擬的站點需要更管origin
ws: true, // 代理websockets
secure: true, // 如果是https接口惫叛,需要配置這個參數(shù)
pathRewrite: {
// 顧名思義倡勇,將/api重寫為 / 此時url變?yōu)?http://192.168.101.110:8888/ 而不是 http://192.168.101.110:8888/api
'^/profile': ''
}
}
}
}
第二步驟
在封裝axios請求中設(shè)置
const service = axios.create({
baseURL: '/profile',//定義要跨域的接口路徑
withCredentials: true,//是否支持跨域
timeout: 500000, // request timeout
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded'
}
});