Spring Boot中,拦截器与跨域同时配置后,跨域会失效。
在prehandle中加入
if("OPTIONS".equals(request.getMethod().toUpperCase())){
return true;
}
遇到OPTIONS请求直接放行。
或者将跨域写为filter
package com.loves.config; 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(){ CorsConfiguration config = new CorsConfiguration(); config.addAllowedHeader("*"); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**",config); return new CorsFilter(configSource); } }
将对象转换为JSON,先引入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency>
之后再用JSON类的toJSONString()方法将对象转换为json字符串