In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to solve the cross-domain problem of ajax". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to solve the cross-domain problem of ajax.
What is ajax Cross-Domain
The principle of ajax Cross-Domain
The cross-domain error occurred in ajax is mainly due to the browser's "same origin policy". For more information, please see
Browser homology policy and its evasion methods (Ruan Yifeng)
Principle of CORS request
CORS is a W3C standard, the full name is "cross-domain resource sharing" (Cross-origin resource sharing). It allows browsers to send XMLHttpRequest requests to cross-source servers, thus overcoming the limitation that AJAX can only be used in the same origin.
Basically all browsers have implemented the CORS standard, in fact, almost all browser ajax requests are based on the CORS mechanism, but the front-end developers may not care about it (so in fact, the CORS solution is mainly about how to implement it in the background).
For CORS, it is highly recommended to read
Detailed explanation of cross-domain resource sharing CORS (Ruan Yifeng)
In addition, an implementation schematic (simplified version) is also arranged here:
How can I tell if it is a simple request?
Browsers divide CORS requests into two categories: simple requests (simple request) and non-simple requests (not-so-simple request). It is a simple request as long as the following two conditions are met at the same time.
The request method is one of three methods: HEAD,GET,POST
The header information of HTTP does not exceed the following fields:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type (limited to three values application/x-www-form-urlencoded, multipart/form-data, text/plain)
Anyone who does not meet the above two conditions at the same time is a non-simple request.
Cross-domain performance of ajax
To be honest, I sorted out an article and then used it as a solution, but it turns out that there are still a lot of people who still don't know how to do it. But can only be time-consuming and labor-consuming debugging. 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, it will be shown as follows: (note that it is an ajax request, please do not say why the http request can, but not ajax, because ajax is accompanied by cross-domain, so only http request ok is not allowed.)
Note: for specific backend cross-domain configuration, please see the outline location.
* phenomenon: No 'Access-Control-Allow-Origin' header is present on the requested resource, and The response had HTTP status code 404
The reasons for this are as follows:
This ajax request is not a simple request, so a pre-check request (OPTIONS) will be sent before the request.
The server-side background interface does not allow OPTIONS requests, so the corresponding interface address cannot be found.
Solution: the backend allows options requests
The second phenomenon: No 'Access-Control-Allow-Origin' header is present on the requested resource, and The response had HTTP status code 405
This phenomenon is different from * *. In this case, the background method allows OPTIONS requests, but some configuration files (such as security configuration) block OPTIONS requests, which leads to this phenomenon.
Solution: the backend shuts down the corresponding security configuration
The third phenomenon: No 'Access-Control-Allow-Origin' header is present on the requested resource, and status 200,
This phenomenon is different from * * and the second. In this case, the server background allows OPTIONS requests, and the interface also allows OPTIONS requests, but there is a mismatch when the headers match.
For example, the origin header check does not match, for example, some header support is missing (such as the common X-Requested-With header), and then the server returns the response to the frontend. When the frontend detects this, the XHR.onerror is triggered, causing the frontend console to report an error.
Solution: add corresponding header support to the backend
Fourth phenomenon: heade contains multiple values'*, *'
The phenomenon is that the http header information of the backend response has two Access-Control-Allow-Origin:*.
To tell you the truth, the main reason for this problem is that people who perform cross-domain configuration do not understand the principle, which leads to repeated configuration, such as:
It is common in the .net background (usually origin is configured once in web.config, and then origin is manually added to the code (for example, the code manually sets the return *))
Common in. Net backend (setting Origin:* in both IIS and project webconfig)
Solution (one-to-one correspondence):
It is recommended to delete the manually added * in the code and only use the * in the project configuration.
It is recommended to delete the configuration under IIS * and use only those in the project configuration.
How to solve the problem of ajax Cross-Domain
Generally speaking, ajax cross-domain solution is solved through JSONP solution or CORS solution, such as the following: (note that JSONP is almost no longer used, so JSONP can learn about it)
Solving Cross-domain problems by JSONP
Jsonp is an old solution to solve cross-domain problems (it is 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 encapsulated class libraries of JSONP to make ajax requests)
Realization principle
JSONP can be used to solve cross-domain solutions mainly because scripts have cross-domain capabilities, and JSONP takes advantage of this. The specific principle is shown in the diagram.
Realization process
The implementation steps of JSONP are roughly as follows (refer to the article in the source)
The client web page requests JSON data from the server by adding an element, which is not restricted by the same origin policy.
Function addScriptTag (src) {var script = document.createElement ('script'); script.setAttribute ("type", "text/javascript"); script.src = src; document.body.appendChild (script);} _ window.onload = function () {addScriptTag (' http://example.com/ip?callback=foo');} function foo (data) {console.log ('response data:' + JSON.stringify (data));}
When requested, the interface address is used as the src of the built script tag, so that when the script tag is built, the final src is what the interface returns.
The interface corresponding to the server adds a function wrapper layer outside the return parameters
Foo ({"test": "testData"})
Because of the script requested by the element, it runs directly as code. At this point, the foo function is called immediately as soon as the browser defines it. JSON data as a parameter is treated as a JavaScript object rather than a string, thus avoiding the step of using JSON.parse.
Note that the data returned by a general JSONP API is different from that returned by an ordinary API, so if the API is to be JSONO compatible, you need to determine whether there is a parameter corresponding to the callback keyword. If so, it is a JSONP request, and return JSONP data, otherwise return normal data.
Attention to use
Based on the implementation principle of JSONP, JSONP can only be a "GET" request, not more complex POST and other requests, so in that case, you have to refer to the following CORS to solve the cross-domain solution (so now it is basically eliminated)
CORS solves cross-domain problems
The principle of CORS has been described above. Here we mainly introduce how the backend should be configured to solve the problem in the actual project (because a large number of project practices are solved by the backend). Here are some common backend solutions:
PHP background configuration
The configuration of PHP backend is the easiest of all backends. Follow these steps:
* * step: configure Php backend to allow cross-domain
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.