Java與前端交互出現(xiàn)跨域問(wèn)題的14種解決方案
1 前端解決方案( 開(kāi)發(fā)環(huán)境代理)
1.1 Webpack開(kāi)發(fā)服務(wù)器代理
// 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請(qǐng)求)
function jsonp(url, callback) { const script = document.createElement('script'); script.src = `${url}?callback=${callback}`; document.body.appendChild(script); } // 后端需要返回類(lèi)似 callbackName(data) 的響應(yīng)
1.4 WebSocket
const socket = new WebSocket('ws://your-backend-url');
1.5 修改瀏覽器安全策略 (僅開(kāi)發(fā)環(huán)境)
Chrome啟動(dòng)參數(shù):--disable-web-security --user-data-dir=/tmp/chrome
2 后端解決方案
2.1 Spring框架解決方案
2.1.1 使用@CrossOrigin注解
@RestController @RequestMapping("/api") @CrossOrigin(origins = "*") // 允許所有來(lái)源 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 過(guò)濾器方式
@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 # 預(yù)檢請(qǐng)求緩存時(shí)間 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以簡(jiǎn)化API開(kāi)發(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 高級(jí)方案
4.1 基于Token的跨域認(rèn)證
// 后端添加響應(yīng)頭 response.setHeader("Access-Control-Expose-Headers", "Authorization"); response.setHeader("Authorization", "Bearer " + token);
4.2 預(yù)檢請(qǐng)求(OPTIONS)處理
@RestController public class OptionsController { @RequestMapping(value = "/**", method = RequestMethod.OPTIONS) public ResponseEntity<?> handleOptions() { return ResponseEntity.ok().build(); } }
4.3 動(dòng)態(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)關(guān)方案,開(kāi)發(fā)環(huán)境中可以使用代理或后端CORS配置。
以上就是Java與前端交互出現(xiàn)跨域問(wèn)題的14種解決方案的詳細(xì)內(nèi)容,更多關(guān)于Java跨域問(wèn)題解決的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringCloud如何引用xxjob定時(shí)任務(wù)
Spring?Cloud?本身不直接支持?XXL-JOB?這樣的定時(shí)任務(wù)框架,如果你想在?Spring?Cloud?應(yīng)用中集成?XXL-JOB,你需要手動(dòng)進(jìn)行配置,本文給大家介紹SpringCloud如何引用xxjob定時(shí)任務(wù),感興趣的朋友一起看看吧2024-04-04超詳細(xì)介紹idea中java程序打jar包的兩種方式
這篇文章主要介紹了超詳細(xì)介紹idea中java程序打jar包的兩種方式一種是可直接執(zhí)行的runnable jar文件,另一種是包含多個(gè)主類(lèi),運(yùn)行時(shí)需要指定主類(lèi)全類(lèi)名的jar包,感興趣的可以了解一下2020-07-07Java計(jì)算Date類(lèi)時(shí)間差實(shí)例代碼演示
最近工作中遇到需要計(jì)算時(shí)間差,這里給大家總結(jié)下,下面這篇文章主要給大家介紹了關(guān)于Java計(jì)算Date類(lèi)時(shí)間差的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12MyBatis中關(guān)于SQL的寫(xiě)法總結(jié)
這篇文章主要介紹了MyBatis中關(guān)于SQL的寫(xiě)法總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08java調(diào)用ffmpeg實(shí)現(xiàn)視頻轉(zhuǎn)換的方法
這篇文章主要介紹了java調(diào)用ffmpeg實(shí)現(xiàn)視頻轉(zhuǎn)換的方法,較為詳細(xì)分析了java視頻格式轉(zhuǎn)換所需要的步驟及具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-06-06Java實(shí)現(xiàn)Fibonacci(斐波那契)取余的示例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)Fibonacci取余的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03springboot @ComponentScan注解原理解析
這篇文章主要介紹了springboot @ComponentScan注解原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02解決Feign切換client到okhttp無(wú)法生效的坑(出現(xiàn)原因說(shuō)明)
這篇文章主要介紹了解決Feign切換client到okhttp無(wú)法生效的坑(出現(xiàn)原因說(shuō)明),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02