1、Nginx配置跨域:
server {listen 80;server_name your-backend-service.com;location / {proxy_pass http://localhost:8080; # Spring Boot应用的内部地址proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;# 添加CORS头部允许指定域名add_header 'Access-Control-Allow-Origin' 'http://example.com';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';# 预检请求响应if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' 'http://example.com';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';add_header 'Access-Control-Max-Age' 1728000;add_header 'Content-Type' 'text/plain charset=UTF-8';add_header 'Content-Length' 0;return 204;}}
}#Access-Control-Allow-Origin:指定允许跨域请求的源。可以是具体的域名(如http://example.com),或者使用*表示允许所有源。但是,当需要携带凭证(如Cookies)时,必须指定具体的域名。
#Access-Control-Allow-Methods:列出允许的HTTP方法,如GET、POST、PUT、DELETE、OPTIONS等。
#Access-Control-Allow-Headers:指定允许在请求中使用的自定义头部,如Content-Type、#Authorization等。
#Access-Control-Allow-Credentials:如果设置为true,则允许跨域请求携带凭证(如Cookies)。当设置此选项时,Access-Control-Allow-Origin不能设置为*,必须指定具体的域名。
#Access-Control-Max-Age:指定预检请求的有效期(以秒为单位),在有效期内,浏览器不会再次发送预检请求。
2、实现WebMvcConfigurer
package com.hmmy.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class CorsConfig implements WebMvcConfigurer {/*** 跨域处理*/@Beanpublic WebMvcConfigurer corsConfigurer() {return new WebMvcConfigurer() {@Overridepublic void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {}// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/**")
// .addResourceLocations("classpath:/resources/","classpath:/static/","classpath:/META-INF/resources/");.addResourceLocations("file:C:/Picture/323223618780001/"); /** windows 系统配置路径*/.addResourceLocations("file:/home/java/"); /** linux 系统配置路径*/
// }@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*"). //允许跨域的域名,可以用*表示允许任何域名使用allowedMethods("*"). //允许任何方法(post、get等)allowedHeaders("*"). //允许任何请求头allowCredentials(true). //带上cookie信息exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果}};}
}
3、使用拦截器
@Component
public class CorsFilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {HttpServletResponse res = (HttpServletResponse) response;res.addHeader("Access-Control-Allow-Credentials", "true");res.addHeader("Access-Control-Allow-Origin", "*");res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {response.getWriter().println("ok");return;}chain.doFilter(request, response);}@Overridepublic void destroy() {}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}
}