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

How to attach cookies to ajax cross-domain requests

Sep 13, 2018 pm 05:26 PM
ajax cookie

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Frequently Asked Questions and Solutions about Cookie Settings Frequently Asked Questions and Solutions about Cookie Settings Jan 19, 2024 am 09:08 AM

Common problems and solutions for cookie settings, specific code examples are required. With the development of the Internet, cookies, as one of the most common conventional technologies, have been widely used in websites and applications. Cookie, simply put, is a data file stored on the user's computer that can be used to store the user's information on the website, including login name, shopping cart contents, website preferences, etc. Cookies are an essential tool for developers, but at the same time, cookie settings are often encountered

How to find cookies in your browser How to find cookies in your browser Jan 19, 2024 am 09:46 AM

In our daily use of computers and the Internet, we are often exposed to cookies. A cookie is a small text file that saves records of our visits to the website, preferences and other information. This information may be used by the website to better serve us. But sometimes, we need to find cookie information to find the content we want. So how do we find cookies in the browser? First, we need to understand where the cookie exists. in browser

See all articles