Home > Web Front-end > JS Tutorial > How to implement ajax cross-domain request with cookies

How to implement ajax cross-domain request with cookies

不言
Release: 2018-09-10 14:29:02
Original
1582 people have browsed it

The content of this article is about how to implement ajax cross-domain requests with cookies. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

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, save User information is also very important. However, 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, ajax generated across domains cannot carry cookie information, which leads to the problem of session and cookie. The user information 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 upper part of the code is the code to solve the cross-domain problem, and the second part is response.setHeader("Access-Control-Allow-Credentials", "true"); This 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, we can easily know that the most important point in the front-end in cross-domain requests is withCredentials:true. This statement is combined with the "Access" set in the background -Control-Allow-Credentials", "true" 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" in the background ", "*"); 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, which means it The value cannot be *. However, when I think about the front-end IP changing when the front-end and back-end are separated, I feel like I am back to the original point. Can't this method be used 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:

The middleware of express framework in nodejs and the analysis of app.use and app.get methods

angular1 Study notes, which contain the view model synchronization process in angularjs

The above is the detailed content of How to implement ajax cross-domain request with cookies. 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