Table of Contents
Question outline" >Question outline
What is ajax cross-domain" >What is ajax cross-domain
The principle of ajax cross-domain" >The principle of ajax cross-domain
CORS request principle" >CORS request principle
How to solve ajax cross-domain" >How to solve ajax cross-domain
JSONP way to solve cross-domain problems" >JSONP way to solve cross-domain problems
Implementation Principle" >Implementation Principle
Implementation process" >Implementation process
CORS solves cross-domain problems" >CORS solves cross-domain problems
PHP background configuration " >PHP background configuration
Node.js background configuration (express framework)" > Node.js background configuration (express framework)
JAVA background configuration" >JAVA background configuration
NET后台配置" >NET后台配置
代理请求方式解决接口跨域问题" >代理请求方式解决接口跨域问题
如何分析ajax跨域" >如何分析ajax跨域
抓包请求数据" >抓包请求数据
示例一(正常的ajax请求)" >示例一(正常的ajax请求)
示例二(跨域错误的ajax请求)" >示例二(跨域错误的ajax请求)
示例三(与跨域无关的ajax请求)" >示例三(与跨域无关的ajax请求)
更多" >更多
写在最后的话" >写在最后的话
Home Backend Development PHP Tutorial The most complete ajax cross-domain solution

The most complete ajax cross-domain solution

Dec 18, 2017 pm 03:32 PM
ajax solution

This article will share with you the most complete ajax cross-domain solution. Ever since I first came into contact with front-end development, the word <span style="font-size: 14px;">cross-domain</span> has always been It reappears around me with a very high frequency. Until now, I have debugged N cross-domain related issues. I also compiled a related article in 2016, but I still feel that something is missing, so I have reorganized it now. one time.

Question outline

Regarding cross-domain, there are N types. This article only focuses on <span style="font-size: 14px;">ajax requests Cross-domain </span>(, Ajax cross-domain is only part of the browser's "same-origin policy", others include Cookie cross-domain, iframe cross-domain, LocalStorage cross-domain, etc., which will not be introduced here), The content is roughly as follows:

  • What is ajax cross-domain

    • Principle

    • Performance (organized some problems encountered and solutions)

  • How to solve ajax cross-domain

    • JSONP way

    • CORS way

    • Proxy request method

  • How to analyze ajax cross-domain

    • http packet capture analysis

    • Some examples

What is ajax cross-domain

The principle of ajax cross-domain

ajax request appears The main reason for the cross-domain error problem is the browser's "same origin policy". You can refer to

Browser Same Origin Policy and How to Avoid It (Ruan Yifeng)

CORS request principle

CORS is a W3C standard, the full name is "Cross-origin resource sharing" (Cross-origin resource sharing). It allows the browser to issue XMLHttpRequest requests to cross-origin servers, thus overcoming the limitation that AJAX can only be used from the same origin.

Basically all current browsers have implemented the CORS standard. In fact, almost all browser ajax requests are based on the CORS mechanism. However, front-end developers may not usually Just concerned (so in fact, the current CORS solution mainly considers how to implement the background).

Regarding CORS, it is highly recommended to read
Detailed explanation of CORS for cross-domain resource sharing (Ruan Yifeng)

In addition, here is also a summary Implementation schematic diagram (simplified version):

The most complete ajax cross-domain solution

##How to judge whether it is a simple request?<span style="font-size: 14px;"></span>

Browsers divide CORS requests into two categories: simple requests and not-so-simple requests. As long as the following two conditions are met at the same time, it is a simple request. <span style="font-size: 14px;"></span>

  • The request method is one of the following three methods: HEAD, GET, POST<span style="font-size: 14px;"></span>

  • HTTP header information does not exceed the following fields: <span style="font-size: 14px;"></span>

    • Accept<span style="font-size: 14px;"></span>

    • Accept-Language<span style="font-size: 14px;"></span>

    • ##Content-Language

      <span style="font-size: 14px;"></span>

    • ##Last-Event-ID
    • <span style="font-size: 14px;"></span>

    • Content-Type (limited to three values ​​application/x-www-form-urlencoded, multipart/form-data, text/plain)
    • <span style="font-size: 14px;"></span>

    #Any request that does not meet the above two conditions at the same time is a non-simple request.

<span style="font-size: 14px;"></span>Ajax cross-domain performance

<span style="font-size: 14px;"></span>To be honest, I compiled an article at first and then used it as a solution, but later I found that it was still Many people still don't know how. We have no choice but to debug it which is time-consuming and labor-intensive. However, even if I analyze it, I will only judge whether it is cross-domain based on the corresponding performance, so this is very important.

When making an ajax request, if there is a cross-domain phenomenon and it is not resolved, the following behavior will occur: (Note, it is an ajax request. Please do not say why http requests are OK but ajax is not, because ajax is accompanied by Cross-domain, so just http request ok is not enough)

Note: Please see the title position for specific back-end cross-domain configuration.

The first phenomenon:<span style="font-size: 14px;">No 'Access-Control-Allow-Origin' header is present on the requested resource</span>, and<span style="font-size: 14px;">The response had HTTP status code 404</span>

The most complete ajax cross-domain solution

## The reasons for this situation are as follows: <span style="font-size: 14px;"></span>

  • This ajax request is a "non-simple request", so a preflight request (OPTIONS) will be sent before the request<span style="font-size: 14px;"></span>

  • The server-side background interface does not allow OPTIONS requests, resulting in the inability to find the corresponding interface address<span style="font-size: 14px;"></span>

## Solution: The backend allows options requests

<span style="font-size: 14px;"></span>

Second phenomenon:

<span style="font-size: 14px;"></span>No 'Access-Control-Allow-Origin' header is present on the requested resource<span style="font-size: 14px;"></span>, and<span style="font-size: 14px;"></span>The response had HTTP status code 405<span style="font-size: 14px;"></span>

The most complete ajax cross-domain solution

This phenomenon is different from the first one. In this case, the background method allows OPTIONS requests, but some configuration files (such as

Security Configuration <span style="font-size: 14px;"></span>), blocking the OPTIONS request will cause this phenomenon<span style="font-size: 14px;"></span>

Solution: Close the corresponding security configuration on the backend

<span style="font-size: 14px;"></span>

The third phenomenon:

<span style="font-size: 14px;"></span>No 'Access-Control-Allow-Origin' header is present on the requested resource<span style="font-size: 14px;"></span>, and status 200<span style="font-size: 14px;"></span>

The most complete ajax cross-domain solution##This phenomenon is different from the first and second ones. In this case, the server-side background allows OPTIONS requests, and the interface also allows OPTIONS requests, but there is a mismatch when the header matches.

<span style="font-size: 14px;"></span>For example, the origin header check does not match, for example, it is missing Support for some headers (such as the common X-Requested-With header), then the server will return the response to the front-end. After the front-end detects this, it will trigger XHR.onerror, causing the front-end console to report an error

<span style="font-size: 14px;"></span>Solution: Add corresponding header support to the backend

<span style="font-size: 14px;"></span>Fourth phenomenon:

heade contains multiple values ​​'* ,*'<span style="font-size: 14px;"></span>

The most complete ajax cross-domain solution

The most complete ajax cross-domain solution##phenomenon Yes, the background response http header information has two

Access-Control-Allow-Origin:*<span style="font-size: 14px;"></span><span style="font-size: 14px;"></span>To be honest, this kind of The main reason for the problem is that people who perform cross-domain configuration do not understand the principles, resulting in repeated configurations, such as:

<span style="font-size: 14px;"></span>

is common in the .net background (generally in the web The origin is configured once in .config, and then the origin is manually added to the code (for example, the code manually sets the return *))
  • <span style="font-size: 14px;"></span>

    commonly found in the .net backend (Set Origin:* in both IIS and the project's webconfig)
  • <span style="font-size: 14px;"></span>

    Solution (one-to-one correspondence):

<span style="font-size: 14px;"></span>

It is recommended to delete the manually added * in the code and only use the ones in the project configuration
  • <span style="font-size: 14px;"></span>

    It is recommended to delete the configuration* under IIS , just use the ones in the project configuration

How to solve ajax cross-domain

Generally, ajax cross-domain solution is solved through JSONP or CORS, as follows: (Note, now it has been solved I almost never use JSONP anymore, so just understand JSONP)

JSONP way to solve cross-domain problems

jsonp solves cross-domain problems It is a relatively old solution (not recommended in practice). Here is a brief introduction (if you want to use JSONP in actual projects, you will generally use JQ and other class libraries that encapsulate JSONP to make ajax requests)

Implementation Principle

The reason why JSONP can be used to solve cross-domain solutions is mainly because

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)

Solution for Win11 unable to install Chinese language pack Solution for Win11 unable to install Chinese language pack Mar 09, 2024 am 09:15 AM

Win11 is the latest operating system launched by Microsoft. Compared with previous versions, Win11 has greatly improved the interface design and user experience. However, some users reported that they encountered the problem of being unable to install the Chinese language pack after installing Win11, which caused trouble for them to use Chinese in the system. This article will provide some solutions to the problem that Win11 cannot install the Chinese language pack to help users use Chinese smoothly. First, we need to understand why the Chinese language pack cannot be installed. Generally speaking, Win11

An effective solution to solve the problem of garbled characters caused by Oracle character set modification An effective solution to solve the problem of garbled characters caused by Oracle character set modification Mar 03, 2024 am 09:57 AM

Title: An effective solution to solve the problem of garbled characters caused by Oracle character set modification. In Oracle database, when the character set is modified, the problem of garbled characters often occurs due to the presence of incompatible characters in the data. In order to solve this problem, we need to adopt some effective solutions. This article will introduce some specific solutions and code examples to solve the problem of garbled characters caused by Oracle character set modification. 1. Export data and reset the character set. First, we can export the data in the database by using the expdp command.

Oracle NVL function common problems and solutions Oracle NVL function common problems and solutions Mar 10, 2024 am 08:42 AM

Common problems and solutions for OracleNVL function Oracle database is a widely used relational database system, and it is often necessary to deal with null values ​​during data processing. In order to deal with the problems caused by null values, Oracle provides the NVL function to handle null values. This article will introduce common problems and solutions of NVL functions, and provide specific code examples. Question 1: Improper usage of NVL function. The basic syntax of NVL function is: NVL(expr1,default_value).

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Common causes and solutions for Chinese garbled characters in MySQL installation Common causes and solutions for Chinese garbled characters in MySQL installation Mar 02, 2024 am 09:00 AM

Common reasons and solutions for Chinese garbled characters in MySQL installation MySQL is a commonly used relational database management system, but you may encounter the problem of Chinese garbled characters during use, which brings trouble to developers and system administrators. The problem of Chinese garbled characters is mainly caused by incorrect character set settings, inconsistent character sets between the database server and the client, etc. This article will introduce in detail the common causes and solutions of Chinese garbled characters in MySQL installation to help everyone better solve this problem. 1. Common reasons: character set setting

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.

Common causes and solutions for Chinese garbled characters in PHP Common causes and solutions for Chinese garbled characters in PHP Mar 16, 2024 am 11:51 AM

Common causes and solutions for PHP Chinese garbled characters. With the development of the Internet, Chinese websites play an increasingly important role in our lives. However, in PHP development, the problem of Chinese garbled characters is still a common problem that troubles developers. This article will introduce the common causes of Chinese garbled characters in PHP and provide solutions. It also attaches specific code examples for readers' reference. 1. Common reasons: Inconsistent character encoding: Inconsistencies in PHP file encoding, database encoding, HTML page encoding, etc. may lead to Chinese garbled characters. database

Explore solutions to abnormal CPU and Sys usage in Linux Explore solutions to abnormal CPU and Sys usage in Linux Mar 01, 2024 pm 05:36 PM

[Title] Explore solutions to abnormal CPU and Sys usage in Linux. In Linux systems, abnormal CPU and Sys usage often make the system run slowly or unstable, causing trouble to users. This article will explore the causes of these anomalies and provide some solutions, as well as specific code examples. Abnormal CPU usage Abnormal CPU usage is usually caused by too many processes running or a certain process occupying too many CPU resources. To solve this problem, you can view the processes running on the system

See all articles