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字符串
本文探讨了在SpringBoot应用中,如何在配置全局拦截器的同时避免跨域请求失效的问题,通过修改预处理逻辑和使用CorsFilter的实例配置来确保跨域功能正常运作。
4万+

被折叠的 条评论
为什么被折叠?



