Home > Web Front-end > JS Tutorial > How to attach cookies to ajax cross-domain requests

How to attach cookies to ajax cross-domain requests

坏嘻嘻
Release: 2018-09-13 17:26:43
Original
1702 people have browsed it

This time I will show you how to solve the problem of cookie loss during Ajax cross-domain access. What are the precautions for solving the problem of cookie loss during Ajax cross-domain access? The following is a practical case, let's take a look.

In the actual development of the project, we will always encounter projects where the front and back ends are separated. In such projects, cross-domain is the first problem to be solved. In addition, saving user information is also It is very important, however, that the method of combining session and cookie is usually used to save user information in the background. In the actual situation of the front end, the ajax generated across domains cannot carry cookie information, which leads to the loss of session and cookie user information. The storage mode is affected. How to solve such a problem? By consulting the information, I will take the ajax request in $http of angularJS as an example.

First, in the background I use the servlet filter to intercept all requests and set the request header:


	// 解决跨越问题
Copy after login
	response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken");
Copy after login
	// 允许跨域请求中携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
Copy after login

The above part of the code is to solve the cross-domain problem The code in question, and the second part of response.setHeader("Access-Control-Allow-Credentials", "true"); is the code that allows cookies to be carried in the backend.


Front-end code:


$scope.login = function () {
                $http({
                    // 设置请求可以携带cookie
                    withCredentials:true,
                    method: 'post',
                    params: $scope.user,
                    url: 'http://localhost:8080/user/login'
                }).then(function (res) {
                    alert(res.data.msg);
                }, function (res) {
                    if (res.data.msg) {
                        alert(res.data.msg);
                    } else {
                        alert('网络或设置错误');
                    }
                })
            }
Copy after login

From the above code, it is not difficult for us to know that in cross-domain requests, in the front-end The most important point is withCredentials:true. This statement, combined with the "Access-Control-Allow-Credentials" and "true" set in the background, can carry cookies in cross-domain ajax requests.


However, I found some problems during my test. When the request was sent, the browser reported the following error

Response to preflight request doesn't pass access control check: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

After consulting relevant information, I discovered that the reason is to solve the cross-domain code response.setHeader("Access-Control- Allow-Origin", "*"); This part conflicts with the part of setting up cross-domain carrying cookies. After checking the relevant information, I found that when setting up cross-domain ajax requests to carry cookies, Access-Control-Allow-Origin must be specified. This means that its value cannot be *. However, when you think about the front-end IP changing when the front-end and back-end are separated, it feels like you are back to the original point. Can't you use this method to solve the problem of ajax cross-domain and carrying cookies?

Next, during the research on the ajax requests I made, I found that in angularJS, the value of the Origin request header in every request is "null". What does this mean? So I changed the background "Access-Control-Allow-Origin", "*" to "Access-Control-Allow-Origin", "null", and the next thing became wonderful, all ajax requests were successful. The accompanying cookie successfully achieved its purpose.


      response.setHeader("Access-Control-Allow-Origin", "null");
Copy after login

Related recommendations:

JavaScript (Ajax) and Cookie Same Origin Policy

Ajax cross-domain request cannot cookie

The above is the detailed content of How to attach cookies to ajax cross-domain requests. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template