1. 后端配置
新建一個CrosConfig.java檔案(配置類),允許任意請求發送
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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域設定
* 2021/10/9 10:57
*/
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
2. 前端配置代理(前后端只要一個配置就行)
vue根目錄下新建一個 vue.config.js 檔案
// 方法一: 當前端只需要請求一個后端(服務)時,可以使用以下這種:
module.exports = {
devServer: {
proxy: 'http://localhost:5000' // 配置代理的服務器地址
}
}
- 優點:配置簡單,請求資源時直接發給前端(8080)即可,
- 缺點:不能配置多個代理,不能靈活的控制請求是否走代理,
- 作業方式:若按照上述配置代理,當請求了前端不存在的資源時,那么該請求會轉發給服務器 (優先匹配前端資源,即當前端存在請求的東西時,則直接回傳前端的東西)
// 方法二:前端需要請求多個后端服務:用以下這種
module.exports = {
devServer: {
proxy: {
'/api': {// 匹配所有以 '/api1'開頭的請求路徑
target: 'http://localhost:5000',// 代理目標的基礎路徑
changeOrigin: true,
pathRewrite: {'^/api': ''} // 代理到服務器的時候,去除api路徑
},
'/api2': {// 匹配所有以 '/api2'開頭的請求路徑
target: 'http://localhost:5001',// 代理目標的基礎路徑
changeOrigin: true,
pathRewrite: {'^/api2': ''}
}
}
}
}
/*
changeOrigin設定為true時,服務器收到的請求頭中的host為:localhost:5000
changeOrigin設定為false時,服務器收到的請求頭中的host為:localhost:8080
changeOrigin默認值為true
*/
- 優點:可以配置多個代理,且可以靈活的控制請求是否走代理,
- 缺點:配置略微繁瑣,請求資源時必須加前綴
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/509635.html
標籤:其他
上一篇:詳解JS中 call 方法的實作
下一篇:axios學習筆記
