springboot2.0项目axios跨域options请求携带自定义header后台接收不到

前台发起请求后报错

Failed to load http://192.168.1.107:8066/talk/queryList: Response to preflight request 
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on 
the requested resource. Origin 'http://192.168.1.107:8080' is therefore not allowed access.

参考了两个文章:

https://www.2cto.com/kf/201711/700228.html

https://www.jianshu.com/p/f37f8c295057

解决办法是:

配置类

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                //是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                .allowedHeaders("*")
                //跨域允许时间
                .maxAge(3600);
    }
}

过滤器里面设置下:

if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
        chain.doFilter(request, response);
}

如果是options请求则不进行那些校验,

因为我这里options请求无法携带头请求,但具体是不是所有的options都无法携带头请求我也不知道,别人告诉我说因为这个options自动生成的所以没有携带头请求,如果自己生成的可以携带

扫描二维码关注公众号,回复: 4734656 查看本文章
package com.qky.qingchi.config;

import com.qky.qingchi.util.CookieUtils;
import com.qky.qingchi.util.TokenUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Configuration
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            chain.doFilter(request, response);
        }

        String cookieToken = CookieUtils.getCookie(req, "token");

        String headerToken = req.getHeader("token");
        System.out.println("headerToken27:" + headerToken);
        if (TokenUtils.notCorrect(headerToken) && !req.getRequestURI().contains("login")) {
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}

之前我没有加

if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
        chain.doFilter(request, response);
}

这行代码,所有请求都去获取token,然后options请求是获取不到header里面的token的,所以会报错,

猜你喜欢

转载自blog.csdn.net/qinkaiyuan94/article/details/82669602