1. 程式人生 > 實用技巧 >後端跨域問題的解決

後端跨域問題的解決

1.spring boot增加全域性配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description 跨域配置
 * @Date 2019/1/27 13:31
 *
*/ @Configuration public class CORSConfig { @Bean public WebMvcConfigurer corsConfigurer(){ return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders(
"*") .allowedMethods("*") .allowedOrigins("*"); } }; } }

或者

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 { @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); final CorsConfiguration corsConfiguration = new CorsConfiguration(); /*是否允許請求帶有驗證資訊*/ corsConfiguration.setAllowCredentials(true); /*允許訪問的客戶端域名*/ corsConfiguration.addAllowedOrigin("*"); /*允許服務端訪問的客戶端請求頭*/ corsConfiguration.addAllowedHeader("*"); /*允許訪問的方法名,GET POST等*/ corsConfiguration.addAllowedMethod("*"); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(urlBasedCorsConfigurationSource); } }

2.nginx 轉發

前後端通過一個nginx進行轉發。這樣前後端就是同源的

3.HttpClient 請求轉發

前端工程寫一箇中間轉發介面httpClient去請求其他不同源的介面,再將資料回傳給前端。

應為中間介面是在前端工程裡面的,所以是同源的,不存在跨域問題。

4.使用註解解決跨域問題

對於spring應用或者springboot應用,一般使用註解都是可以解決跨域問題。@CrossOrggin

5.response 新增 header

我們在 Servlet 請求返回時新增如下程式碼:

resp.setHeader("Access-Control-Allow-Origin", "*");

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");