写用户匹配系统遇到的bug,axios发送请求不携带cookie

鱼皮的直播回放中的解决方法是在自定义的axios的文件中加入以下代码即可解决

myAxios.defaults.withCredentials = true;

而我也试着加入后,看请求头的内容中并没有cookie的字样,随后我就又试了试在前端配置代理的方法,配置了代理后,发现请求头携带cookie这个参数了,到此为止我以为我解决了问题,但随后我便开始登录的一套流程,然而这套流程确实走不通的,我后端找不到前端传来的cookie,但可以确定的是后端并没有问题,后面我便想到我后端处理跨域的方式和鱼皮的不一样,然后再一通百度,直到百度了这个问题(axios.defaults.withcredentials true 不起作用)才出现了得出答案:


withCredentials 在 AJAX 请求时不能将对 CORS 安全性的策略进行牺牲,默认情况下不允许跨站访问。因此您需要在后台服务器上配置允许跨站访问请求。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
//解决跨域工具类
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedHeaders(CorsConfiguration.ALL)
.allowedMethods(CorsConfiguration.ALL)
.allowCredentials(true)
.maxAge(3600); // 1小时内不需要再预检(发OPTIONS请求)
}

添加了如下代码
/**
* 前端发送请求并且携带cookie的情况下需要添加一下配置
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
return true;
}
}).addPathPatterns("/api/**");
}

}


至此,便解决了axios发送请求时不携带cookie的问题





0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
wind
下载 APP