解决react中aixos请求头携带token跨域请求拒绝

 const token = localStorage.getItem("blog-key")
    const header={Authorization:`Bearer ${token}`}
    const res = await http.post('/comment/add', commentParam,header)
请求报跨域错误,它发生在一个网页请求另一个域名下的网页,浏览器出于安全策略,限制了一个网页获取从同一域名下的数据,以防止恶意脚本攻击
   @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/comment/add");
        WebMvcConfigurer.super.addInterceptors(registry);
后端也对请求路径进行拦截
 @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod))
            return true;//访问静态找资源
        String token=request.getHeader("authorization");

        if (StringUtils.isBlank(token)){
            Result result=new Result(400,"请登录",null);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSON(result));
            return false;
此时需要配置后端CORS(跨域资源共享)
 @Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}
上述代码表示允许来自 http://localhost:8080的请求访问以/api开头的所有请求。允许的请求方法为GET、POST、PUT、DELETE,允许的请求头为任意值,允许携带cookie,缓存时间为3600秒。
需要注意的是,上述代码中的addCorsMappings方法是WebMvcConfigurer接口中的一个方法,需要实现该接口并重写该方法。该方法中的CorsRegistry对象用于配置跨域请求的详细参数。在该方法中可以配置允许跨域请求的源、允许的请求方法、允许的请求头等参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值