跨域请求携带cookie的实现

跨域时,前端向服务器发起请求时,需要将 XMLHttpRequest 对象的 withCredentials 属性设置为 true,如下所示:

         $.ajax({
                type: "POST",
                url: url,
                data:{},
                dataType: 'json',
                crossDomain: true, 
                xhrFields: {
                    withCredentials: true 
                },
                success: function (data) {
                   
                },
                error: function (data) {
                   
                }
            });

后端设置如下:

private boolean allOrigin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = request.getHeader("Origin");
        if (!StringUtils.isEmpty(url)) {          
                response.addHeader("Access-Control-Allow-Origin", url);
                response.addHeader("Access-Control-Allow-Credentials", "true");           
        }
        return true;
    }

 

你可能感兴趣的:(Web前端)