Java與前端交互出現(xiàn)跨域問題的14種解決方案
1 前端解決方案( 開發(fā)環(huán)境代理)
1.1 Webpack開發(fā)服務器代理
// vue.config.js 或 webpack.config.js module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }
1.2 Vite代理配置
// vite.config.js export default defineConfig({ server: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } })
1.3 JSONP (僅限GET請求)
function jsonp(url, callback) { const script = document.createElement('script'); script.src = `${url}?callback=${callback}`; document.body.appendChild(script); } // 后端需要返回類似 callbackName(data) 的響應
1.4 WebSocket
const socket = new WebSocket('ws://your-backend-url');
1.5 修改瀏覽器安全策略 (僅開發(fā)環(huán)境)
Chrome啟動參數(shù):--disable-web-security --user-data-dir=/tmp/chrome
2 后端解決方案
2.1 Spring框架解決方案
2.1.1 使用@CrossOrigin注解
@RestController @RequestMapping("/api") @CrossOrigin(origins = "*") // 允許所有來源 public class MyController { // 控制器方法 }
2.1.2 全局CORS配置
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000", "http://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
2.1.3 過濾器方式
@Bean public FilterRegistrationBean<CorsFilter> corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:3000"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new FilterRegistrationBean<>(new CorsFilter(source)); }
2.2 Spring Boot特定配置
application.properties配置
# 允許的源 cors.allowed-origins=http://localhost:3000,http://example.com # 允許的方法 cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS # 允許的頭部 cors.allowed-headers=* # 是否允許憑證 cors.allow-credentials=true # 預檢請求緩存時間 cors.max-age=3600
2.3 Spring Security解決方案
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() // 其他安全配置 .csrf().disable(); // 通常需要禁用CSRF以簡化API開發(fā) } @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000")); configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("*")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
3 生產(chǎn)環(huán)境解決方案
Nginx反向代理
server { listen 80; server_name yourdomain.com; location /api { proxy_pass http://backend-server:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { root /path/to/frontend/dist; try_files $uri $uri/ /index.html; } }
4 高級方案
4.1 基于Token的跨域認證
// 后端添加響應頭 response.setHeader("Access-Control-Expose-Headers", "Authorization"); response.setHeader("Authorization", "Bearer " + token);
4.2 預檢請求(OPTIONS)處理
@RestController public class OptionsController { @RequestMapping(value = "/**", method = RequestMethod.OPTIONS) public ResponseEntity<?> handleOptions() { return ResponseEntity.ok().build(); } }
4.3 動態(tài)允許源
@Bean public CorsFilter corsFilter() { return new CorsFilter(new UrlBasedCorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { CorsConfiguration config = new CorsConfiguration(); String origin = request.getHeader("Origin"); if (allowedOrigins.contains(origin)) { // 檢查是否在允許列表中 config.addAllowedOrigin(origin); config.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS")); config.setAllowedHeaders(Arrays.asList("*")); config.setAllowCredentials(true); } return config; } }); }
選擇哪種解決方案取決于具體需求、安全要求和部署環(huán)境。生產(chǎn)環(huán)境中推薦使用Nginx反向代理或API網(wǎng)關方案,開發(fā)環(huán)境中可以使用代理或后端CORS配置。
以上就是Java與前端交互出現(xiàn)跨域問題的14種解決方案的詳細內(nèi)容,更多關于Java跨域問題解決的資料請關注腳本之家其它相關文章!
相關文章
java調(diào)用ffmpeg實現(xiàn)視頻轉(zhuǎn)換的方法
這篇文章主要介紹了java調(diào)用ffmpeg實現(xiàn)視頻轉(zhuǎn)換的方法,較為詳細分析了java視頻格式轉(zhuǎn)換所需要的步驟及具體實現(xiàn)技巧,需要的朋友可以參考下2015-06-06Java實現(xiàn)Fibonacci(斐波那契)取余的示例代碼
這篇文章主要介紹了Java實現(xiàn)Fibonacci取余的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03springboot @ComponentScan注解原理解析
這篇文章主要介紹了springboot @ComponentScan注解原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02解決Feign切換client到okhttp無法生效的坑(出現(xiàn)原因說明)
這篇文章主要介紹了解決Feign切換client到okhttp無法生效的坑(出現(xiàn)原因說明),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02