Home > Article > Web Front-end > In-depth understanding of CORS cross-domain (code example)
This article brings you an in-depth understanding of CORS cross-domain (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
When asked about data interaction in interviews, they often ask how to handle cross-domain processing. Most people will answer JSONP, and then the interviewer will ask: "What are the shortcomings of JSONP?" At this time, the pitfall comes. If the interviewer says that it supports GET method, then the interviewer will ask, what if POST What should I do if I send a request? Interviewers with a solid foundation will say that using CORS cross-domain, while those without a solid foundation may shake their heads.
This is not over yet. If the company is more formal or cares about technical skills, and you are interviewing for an important position, and HR wants to cut your salary, it will make up for it. What are the problems with CORS cross-domain? ? At this time, there are not many people who can answer. Even if you answer that the compatibility is not good and you need IE10 browser, the other party will still have something to say, so how to deal with the compatibility? The candidates will have nothing to say, or they will be passed away. Even if they stay, they will have no confidence when negotiating salary.
CORS cross-domain is really a powerful tool for the interviewer to pass one person.
Why is this so?
1. There are not many cases where CORS requests are encountered. Developers rarely use this scenario, and most of them are handled by JSONP.
2. Developers’ own skills are not solid, they have a lazy mentality, and they usually have no awareness and willingness to improve their technical level.
3. There are few relevant learning materials, and it is difficult for pure front-end novices to build a testable environment.
Faced with this obstacle, we will completely solve it today, so that it will no longer be our weakness, but a highlight that demonstrates our technical strength.
First of all, what is CORS?
It allows the browser to issue XMLHttpRequest requests to cross-origin servers, thereby overcoming the limitation that AJAX can only be used from the same origin.
2.Higher security than JSOP
3. There are relatively few things to do on the front end
2. Server support is required
3. It’s a little complicated to use. How to use it?
nbsp;html> <meta> <meta> <meta> <title>CORS跨域请求</title> <script> function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { xhr = new XDomainRequest(); xhr.open(method, url); } else { xhr = null; } return xhr; } window.onload = function () { var oBtn = document.getElementById('btn1'); oBtn.onclick = function () { var xhr = createCORSRequest("get", "http://wpdic.com/cors.php"); if (xhr) { xhr.onload = function () { var json = JSON.parse(xhr.responseText); alert(json.a); }; xhr.onerror = function () { alert('请求失败.'); }; xhr.send(); } }; }; </script> <input>Notes: 1. The above code is compatible with IE8 because it uses XDomainRequest2. You can treat other codes as XMLHttpRequset Use it, don't think about 2.0 or not 2.03. If you want to post data, you can do it in xhr.send()4. It is not recommended that you study "simple methdod" here For knowledge of classes, you only need to understand the code and be able to use it. It’s not too late to check if you encounter problems.Backend part:
<?php header('content-type:application:json;charset=utf8'); header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:GET,POST'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Headers:x-requested-with,content-type'); $str = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo $str; ?>Notes:1.Access- Control-Allow-Origin:
means allowing cross-domain access from any domain name. If you need to specify a domain name to allow cross-domain access, just change Access-Control-Allow-Origin:
to Access-Control-Allow- Origin: Allowed domain names, this should also be done in actual work. 2. Access-Control-Allow-Methods: GET, POST stipulates the allowed methods. It is recommended to control it more strictly and do not let go of permissions such as DELETE at will.2.Access-Control-Allow-Credentials
This field is optional. Its value is a Boolean value indicating whether to allow sending cookies. By default, cookies are not included in CORS requests. Set to true, which means that the server explicitly allows the cookie to be included in the request and sent to the server. This value can only be set to true. If the server does not want the browser to send cookies, just delete this field. Finally, common interview questions: What are the differences between the application scenarios of CORS and JSONP? CORS requires simultaneous support from the browser (>IE10) and the server. It is a fundamental cross-domain solution and is automatically completed by the browser. The advantage is that it is more powerful and supports various HTTP Methods. The disadvantage is that the compatibility is not as good as JSONP.The above is the detailed content of In-depth understanding of CORS cross-domain (code example). For more information, please follow other related articles on the PHP Chinese website!