常用解決跨域問題的方案
後端配置cors
/**
* 使用CORS解決跨域問題
* @author rsw
*/
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) *默認所有ip和端口都可以訪問,也可以設置固定
config.addAllowedOrigin("*");
//2) 是否發送Cookie信息
config.setAllowCredentials(true);
//3) 允許的請求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允許的頭信息
config.addAllowedHeader("*");
// 5)有效時長
config.setMaxAge(3600L);
//2.添加映射路徑,我們攔截一切請求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
前端問題
vue官方提供的解決跨域問題是配置代理。
其實這樣配置一般就可以解決前端的跨域問題,但是當時不知道怎麼的就在vue.config.js配置了代理,代理配置如下:
module.exports = {
"transpileDependencies": [
"vuetify"
],
publicPath: './', //vue3 解決部署到服務器白屏問題 '/' => ''
outputDir:'dist',
devServer: {
// 項目運行時候的端口號
host: "127.0.0.1",
port: 8089,
proxy: {
'/api': {
target: 'http://118.89.143.27:8090',//後臺接口
ws: true, //如果要代理websockets
secure:false, // 使用的是http協議則設置爲false,https協議則設置爲true
changeOrigin: true, //將選項changeOrigin設置true爲基於名稱的虛擬託管站點。
pathRewrite: { //重寫路徑 比如'/api/aaa/ccc'重寫爲'/aaa/ccc'
'^/api': '/api'
}
}
}
},
//警告 webpack 的性能提示
configureWebpack : {
performance: {
hints:'warning',
//入口起點的最大體積 整數類型(以字節爲單位)
maxEntrypointSize: 50000000,
//生成文件的最大體積 整數類型(以字節爲單位 300k)
maxAssetSize: 30000000,
//只給出 js 文件的性能提示
assetFilter: function(assetFilename) {
return assetFilename.endsWith('.js');
}
}
}
};
proxy配置主要是將8089端口代理到8090後端端口
在本地運行沒有問題,但是部署到服務器上,訪問後端接口狀態是200,但是放回數據有問題,顯示“”“We're sorry but XX doesn't work properly without JavaScript enabled”
百度了很多關於這個問題的解決方式,主要有兩種,一個是修改publicPath
,另一種是修改nginx的配置,但是都不起作用。
最後經過各種嘗試,才發現是proxy
的代理問題
解決
刪除proxy
的代理配置,並配置axios的默認路徑即可解決:
axios.defaults.baseURL = 'http://服務器ip:8090/api';
後端配置跨域,前端其實可以不進行配置也可以。