前端配置
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/");
}
}