問題描述:
前後端分離的項目,前段node+vue。在請求服務端某接口時,需要帶cookie,於是設置:
axiosck.defaults.withCredentials = true。
導致調用後臺接口時,後臺接口數據正常返回,但是前段識別爲跨域,拿不到返回數據。報錯如下:
Failed to load http://192.168.0.222/downLoad/DownLoadCheck?fileIds=855: Response to
preflight request doesn't pass access control check: The value of the 'Access-Control-
Allow-Origin' header in the response must not be the wildcard '*' when the request's
credentials mode is 'include'. Origin 'http://192.168.0.222:9527' is therefore not allowed
access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by
the withCredentials attribute.
解決方法一:需要後臺配置Origin來配合。不靈活,這裏不推薦。
解決方法二:配置代理(推薦)
vue.config.js:
module.exports = {
runtimeCompiler: true,
publicPath: '/', // 設置打包文件相對路徑
devServer: {
// open: process.platform === 'darwin',
// host: 'localhost',
port: 8071,
// open: true, //配置自動啓動瀏覽器
proxy: {
'/proxyApi': {
target: 'http://192.168.0.222:10002/', // 對應自己的接口
changeOrigin: true,
ws: true,
pathRewrite: {
'^/proxyApi': ''
}
}
}
},
}
解釋:proxy:代理配置。
/proxyApi:自己定義一個代理名稱,將來調用接口時使用此字符串代替target中的值
target: 目標代理接口地址,一版寫到域名/IP+port即可。(我這裏端口本來是80,爲了演示代碼暫時寫爲10002)
pathRewrite:是指定是否將 /proxyApi替換,並指定爲替換的值。這裏是替換爲空。
請求方式:
axios.post('/proxyApi/downLoad/DownLoadCheck?fileIds=855', {
fileIds: 855,
fileType:1
}).then((res) => {
console.log(res)
})
此時,雖然請求發送到了:http://localhost:8080/proxyApi/downLoad/DownLoadCheck?fileIds=855,控制檯顯示請求的地址爲:http://localhost:8080/proxyApi/downLoad/DownLoadCheck?fileIds=855。但是已經代理到了地址:http://192.168.0.222:10002/downLoad/DownLoadCheck?fileIds=855。親測可用。
完善:通過配置將請求地址配置到.env文件中實現不同環境中的動態加載。實現不修改代碼切換環境。
可改寫爲:
module.exports = {
runtimeCompiler: true,
publicPath: '/', // 設置打包文件相對路徑
devServer: {
// open: process.platform === 'darwin',
// host: 'localhost',
port: 8071,
// open: true, //配置自動啓動瀏覽器
proxy: {
'/proxyApi': {
target: process.env.VUE_APP_ERMS_API, // 對應自己的接口
changeOrigin: true,
ws: true,
pathRewrite: {
'^/proxyApi': ''
}
}
}
},
}
.env文件配置方法參照一下鏈接。
https://blog.csdn.net/CaptainJava/article/details/103861623