1.普通跨域请求解决方案
①请求接口添加注解
@CrossOrigin(origins = “http://127.0.0.1:8020“, maxAge = 3600)
说明:origins = “http://127.0.0.1:8020“ origins值为当前请求该接口的域
②通用配置
方案一:
在springboot应用中,使用cors全局配置,需要定义一个配置类CORSConfig,继承 WebMvcConfigurationSupport ,并重写addCorsMappings 方法。
package com.springboot_login.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;/*** 设置跨域请求*/@Configurationpublic class CORSConfig extends WebMvcConfigurationSupport {@Overrideprotected void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").//允许所有的访问请求(访问路径)allowedMethods("*").//允许所有的请求方法访问该跨域资源服务器allowedOrigins("*").//允许所有的请求域名访问我们的跨域资源allowedHeaders("*");//允许所有的请求header访问super.addCorsMappings(registry);}}
注意:在springboot2.X版本后,继承的类是 WebMvcConfigurationSupport
配置的详细信息说明如下:
- addMapping :配置可以被跨域的路径,可以任意配置,可以具体到直接请求路径。
- allowedMethods :允许所有的请求方法访问该跨域资源服务器,如:POST、GET、PUT、DELETE等。
- allowedOrigins :允许所有的请求域名访问我们的跨域资源,可以固定单条或者多条内容,如:“http://www.aaa.com”,只有该域名可以访问我们的跨域资源。
- allowedHeaders :允许所有的请求header访问,可以自定义设置任意请求头信息.。
方案二:
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;@Configurationpublic class CorsConfig {private CorsConfiguration buildConfig() {CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用corsConfiguration.addAllowedHeader("*"); // 2允许任何头corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)return corsConfiguration;}@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", buildConfig()); // 4return new CorsFilter(source);}}
2.ajax自定义headers的跨域请求
$.ajax({type:"GET",url:"http://localhost:8766/main/currency/sginInState",dataType:"JSON",data:{uid:userId},beforeSend: function (XMLHttpRequest) {XMLHttpRequest.setRequestHeader("Authorization", access_token);},success:function(res){console.log(res.code)}})
此时请求http://localhost:8766/main/currency/sginInState接口发现OPTIONS http://localhost:8766/main/currency/sginInState 500错误,普通跨域的解决方案已经无法解决这种问题,为什么会出现OPTIONS请求呢?
原因
浏览器会在发送真正请求之前,先发送一个方法为OPTIONS的预检请求 Preflighted requests 这个请求是用来验证本次请求是否安全的,但是并不是所有请求都会发送,需要符合以下条件:
- 请求方法不是GET/HEAD/POST
- POST请求的Content-Type并非application/x-www-form-urlencoded, multipart/form-data, 或text/plain
- 请求设置了自定义的header字段
对于管理端的接口,我有对接口进行权限校验,每次请求需要在header中携带自定义的字段(token),所以浏览器会多发送一个OPTIONS请求去验证此次请求的安全性。
为何OPTIONS请求是500呢?
OPTIONS请求只会携带自定义的字段,并不会将相应的值带入进去,而后台校验token字段时 token为NULL,所以验证不通过,抛出了一个异常。
那么我们现在来解决这种问题:
① spring boot项目application.yml中添加
spring:mvc:dispatch-options-request: true
②添加过滤器配置
第一步:手写RequestFilter请求过滤器配置类此类需要实现HandlerInterceptor类,HandlerInterceptor类是org.springframework.web.servlet.HandlerInterceptor下的。
具体代码实现:
@Componentpublic class RequestFilter implements HandlerInterceptor {public boolean preHandler(HttpServletRequest request,HttpServletResponse response,Object handler){response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Credentials", "true");response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");response.setHeader("Access-Control-Max-Age", "86400");response.setHeader("Access-Control-Allow-Headers", "Authorization");// 如果是OPTIONS请求则结束if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {response.setStatus(HttpStatus.NO_CONTENT.value());return false;}return true;}}
第二步:手写MyWebConfiguration此类需要继承WebMvcConfigurationSupport。
注意:WebMvcConfigurationSupport是2.x版本以上的,1.x版本为WebMvcConfigurerAdapter 。
@Componentpublic class MyWebConfiguration extends WebMvcConfigurationSupport{@Resourceprivate RequestFilter requestFilter;@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 跨域拦截器registry.addInterceptor(requestFilter).addPathPatterns("/**");}}
