背景
Vue3.0通过axios请求后台资源时出现了跨域的问题
前端一般在开发时可以通过配置反向代理来解决资源跨域问题,但是最近主要是在撸SpringBoot相关的知识,所以就通过在后端配置CORS(跨域资源共享)来解决,新建配置类CorsConfig.java
package com.zzq.smadmin.common;
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;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//.allowCredentials(true)
.allowedOrigins("*")
.allowedMethods("GET", "POST", "OPTIONS")
.maxAge(3600);
}
};
}
}
然后重启,以为就搞定了,发现还是一样的结果,问题根本没有解决。
排查发现是浏览器为了安全实际上发起了两次请求,第一次为options请求,第二次才是get/psot...
请求,在options请求中,是不会携带请求头参数的,所以在拦截器上获取请求头为空。
解决方法:
在全局拦截器中增加判断,如果是options请求时,直接返回true,问题解决。
// 如果是 OPTIONS 请求,返回true
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
return true;
}
总结
学习就是一个踩坑填坑的过程,加油!