【开发心得】Vue axios跨域携带cookie
  OIW0KlaMcRRl 2023年11月28日 10 0


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

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月28日 0

暂无评论

推荐阅读
OIW0KlaMcRRl
最新推荐 更多

2024-05-17