Home  >  Article  >  Web Front-end  >  In-depth understanding of CORS cross-domain (code example)

In-depth understanding of CORS cross-domain (code example)

不言
不言forward
2018-11-27 15:00:362625browse

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?

In-depth understanding of CORS cross-domain (code example)

##CORS is a W3C standard, the full name is "Cross-domain Resource Sharing" (Cross-origin resource sharing).

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.

Advantages and Disadvantages

Advantages:

1.Supports POST and all HTTP requests

2.Higher security than JSOP
3. There are relatively few things to do on the front end

Disadvantages:

1. Not compatible with older versions of browsers, such as IE9 and below

2. Server support is required
3. It’s a little complicated to use. How to use it?

Front-end part:

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(&#39;btn1&#39;);
            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(&#39;请求失败.&#39;);
                    };
                    xhr.send();
                }
            };
        };
    </script>


    <input>

Notes:

1. The above code is compatible with IE8 because it uses XDomainRequest

2. You can treat other codes as XMLHttpRequset Use it, don't think about 2.0 or not 2.0

3. 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(&#39;content-type:application:json;charset=utf8&#39;);
header(&#39;Access-Control-Allow-Origin:*&#39;);
header(&#39;Access-Control-Allow-Methods:GET,POST&#39;);
header(&#39;Access-Control-Allow-Credentials: true&#39;);
header(&#39;Access-Control-Allow-Headers:x-requested-with,content-type&#39;);
$str = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;; 
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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete