vue專案解決axios跨域問題
阿新 • • 發佈:2021-11-30
vue專案解決axios跨域問題
1、在專案根目錄新建vue.config.js
檔案
新版本的vuecli已經不會預設新增vue.config.js
檔案,需要手動建立。
2、編輯vue.config.js
將以下檔案新增至vue.config.js中
module.exports = { devServer: { host: '0.0.0.0', open: true, proxy: { // detail: https://cli.vuejs.org/config/#devserver-proxy '/api': { target: `http://localhost:18080/`, changeOrigin: true, pathRewrite: { '^/api': '' } } }, disableHostCheck: true } }
3、效果
-
所有以/api開頭的請求都會預設訪問
http://localhost:18080/
,雖然瀏覽器中顯示的還是localhost:前端埠/api/xx
,但是真正訪問的其實是http://localhsot:18080/xx
-
如果想保留/api,可以在
pathRewrite
中'^/api': ''
修改為'^/api': '/api'
-
如果想代理所有請求,可以將
proxy
內的'/api'
修改為/
,將pathRewrite
內的'^/api': ''
修改為'^/': ''
Java程式碼解決跨域
增加以下配置類
package cn.xxx.xxx.xxx; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** 跨域配置 */ @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); // 1 設定訪問源地址 corsConfiguration.addAllowedOrigin("*"); // 2 設定訪問源請求頭 corsConfiguration.addAllowedHeader("*"); // 3 設定訪問源請求方法 corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 4 對介面配置跨域設定 source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }