axios 设置withCredentials,跨域协带cookie

1,944 阅读1分钟

[# axios设置withCredentials导致“跨域”的解决方案](www.cnblogs.com/h2zZhou/p/1…)

报错 has been blocked by CORS policy: Response to preflight request doesn‘t pass access control check

谷歌浏览器会发送两次请求,第一次是preflight请求,之所以会发这个请求是为了保证当前调用接口的有效性,避免资源浪费,确保有效链接。所以后台需要处理option

        HttpServletRequest request = (HttpServletRequest)req;
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

axios 设置withCredentials,表示跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等),也可以简单的理解为,当前请求为跨域类型时是否在请求中协带cookie

withCredentials的情况下,后端要设置Access-Control-Allow-Origin为你的源地址,
例如[http://localhost](http://localhost/):8080,不能是*,
而且还要设置header(‘Access-Control-Allow-Credentials: true’);