vue + springboot 前后端分离,遇到的第一个坑就是:跨域问题
本地开发,都是localhost,但是由于端口不同,导致出现跨域问题。
网上搜索,解决方法(三种,尝试了后两种,亲测,都可以解决):
第一种方式:
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 {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
这种方式是全局配置的,网上也大都是这种解决办法,但是很多都是基于旧的spring版本,比如:
Spring Boot如何解决前端的Access-Control-Allow-Origin跨域问题
文中WebMvcConfigurerAdapter在spring5.0已经被标记为Deprecated,点开源码可以看到:
/**
* An implementation of {@link WebMvcConfigurer} with empty methods allowing
* subclasses to override only the methods they're interested in.
*
* @author Rossen Stoyanchev
* @since 3.1
* @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
* possible by a Java 8 baseline) and can be implemented directly without the
* need for this adapter
*/
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}
像这种过时的类或者方法,spring的作者们一定会在注解上面说明原因,并告诉你新的该用哪个,这是非常优秀的编码习惯,点赞!
spring5最低支持到jdk1.8,所以注释中明确表明,你可以直接实现WebMvcConfigurer接口,无需再用这个适配器,因为jdk1.8支持接口中存在default-method。
该方式未测试
第二种方式:
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}
第三种方式:
@Slf4j
@RestController
public class loginController {
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
@RequestMapping(value = "/api/login",method = RequestMethod.POST)
public String login(){
log.info("**************身份验证****************");
return "success";
}
}
使用@CrossOrigin标签,并同时设置请求方法 POST / GET 。
参数:allowCredentials为true时,返回的响应头AccessControlAllowCredentials属性才设置为true,允许客户端携带验证消息。
allowedHeaders = "*"表示允许所有请求头通过。
在使用第三种方式时,提示jdk版本过低,需更改jdk版本1.8.
参考:https://segmentfault.com/a/1190000019550329?utm_source=tag-newest