【开发心得】Vue axios跨域携带cookie
前端配置
axios默认发送请求是不携带cookie的,所以需要加上下面这句 axios.defaults.withCredentials = true;
import axios from 'axios';
axios.defaults.withCredentials = true; // 允许携带cookie
// 创建axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_API_SERVER_ADDRESS,
timeout: Config.timeout, // 请求超时时间
});
后端允许跨域处理配置(Springboot2.x 如果是1.x,翻一翻我其他的文章。)
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8080 //这里不能用*,需要动态设置为请求头中的地址
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.file.Paths;
@Configuration
@EnableWebMvc
public class ConfigurerAdapter implements WebMvcConfigurer {
private final long MAX_AGE_SECS = 3600;
@Value("${file.avatar}")
private String avatar;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedOrigins("*")
.allowCredentials(true) // 开启跨域支持cookie
.allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
.maxAge(MAX_AGE_SECS);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String avatarUtl = Paths.get(avatar).normalize().toUri().toASCIIString();
registry.addResourceHandler("/api/admin/users/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0);
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)