美文网首页
记录一下前端设置 axios.defaults.withCred

记录一下前端设置 axios.defaults.withCred

作者: CodeYang | 来源:发表于2022-01-21 16:09 被阅读0次

    记录一下前端设置 axios.defaults.withCredentials = true 的报错

    请求报错:
    Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

    解决方式1:只能解决一个接口

    在后端controller请求的方法中设置

    1. Access-Control-Allow-Origin 值对应前端地址,localhost和127.0.0.1是不一样的,注意看你的是什么


      image.png
    2. Access-Control-Allow-Credentials 设置为 true

    即可解决

        @RequestMapping(value = "/getFileList")
        public List<FileVO> getFileList(HttpServletResponse response){
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            //User user = (User) SecurityUtils.getSubject().getPrincipal();//user.getId()
            List<FileVO> fileVOList = fileDao.findFileListByParentId(1, 0);
            return fileVOList;
        }
    

    解决方式2:全局配置

    @Component
    @WebFilter(urlPatterns = "/*", filterName = "CorsFilter")
    public class CorsFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            HttpServletRequest reqs = (HttpServletRequest) req;
            String curOrigin = reqs.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            response.setHeader("Access-Control-Max-Age", "3600");
            chain.doFilter(req, res);
        }
    
        @Override
        public void destroy() {}
    
    }
    
    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*")
                    .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                    .allowCredentials(true).maxAge(3600);
        }
    }
    

    相关文章

      网友评论

          本文标题:记录一下前端设置 axios.defaults.withCred

          本文链接:https://www.haomeiwen.com/subject/fjrjhrtx.html