Common cross domain solutions at the front end

Posted by HeinekenBeer on Tue, 25 Jan 2022 15:42:37 +0100

catalogue

preface

Cross domain

Cross domain solutions

I Modify local HOST:

II JSONP

III CORS

Quad proxy

preface

Send request XMLHttpRequest(ajax, $ajax, axois),fetch

http://192.168.0.103:8080/

file:///F://vue Stage / Vue Engineering/_ systerm/public/index. The HTML: File protocol does not allow sending ajax requests

In normal projects, there are few requirements for homologous requests. When the server is deployed, it is separated (web server and data server). It calls the third-party platform interface. When developing locally, it previews the project on its own computer, and the data interface requests other servers

Cross domain development and project deployment are deployed to the same service on the same server (production source)

For projects that are not separated from the front end and the back end, the background service will also be started locally during development, so the development is also of the same origin and the deployment is also of the same origin

Full stack development is based on SSR rendering (js+nodejs), which is also homologous

Cross domain

The browser has security policy restrictions. By default, cross domain requests are not allowed (web page address vs request interface address protocol, domain name and port number. One inconsistency among the three is cross domain)

Cross domain solutions

I Modify local HOST:

The development is cross domain, but the deployment is homologous. We just need to solve the cross domain problem of development

  • DNS resolution -- > find the local DNS cache record (find it in the local host file)
  • Enter www.baidu.com in the address bar of the client browser com
  • host configuration: www.baidu.com com:80  127.0.0.1:80

This ensures that the hungry browser is www.baidu.com COM, but we visited the locally developed project. On this basis, we went to www.baidu.com COM / user / list sends a request, which is equivalent to cheating the browser and making the browser think I am homologous

II JSONP

The src request resource file of the script tag (based on the GET request method) does not have cross domain restrictions

The principle of JSONP is to use this mechanism,

It can only be GET requests, which must be supported by the server

Create a global function and send the function to the server through question mark parameter passing

Code

  <script>
        (function () {
            window['fn'] = function fn(result) {
                console.log(result);
            };
        })();
    </script>
    <script src="https://www.baidu. com/sugrec? Prod = PC & WD = Zhou Dongyu & CB = FN "> < / script >

Encapsulating jsonp

Encapsulating jsonp based on promise management

  • 1. Initialization parameter, no default: params=null, function name is callback
  • 2. Create global function
  • 3. Processing url: splice the parameter function name to the end of the url based on the question mark parameter form
  • 4. Send request: create a script tag and insert it into the page
(function () {
    // Detect whether it is a pure object
    const isPlainObject = function isPlainObject(obj) {
        let proto, Ctor;
        if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") return false;
        proto = Object.getPrototypeOf(obj);
        if (!proto) return true;
        Ctor = proto.hasOwnProperty('constructor') && proto.constructor;
        return typeof Ctor === "function" && Ctor === Object;
    };

    // Change ordinary objects into URLENCODED format strings
    const stringify = function stringify(obj) {
        let str = ``,
            keys = Object.keys(obj).concat(Object.getOwnPropertySymbols(obj));
        keys.forEach(key => {
            str += `&${key}=${obj[key]}`;
        });
        return str.substring(1);
    };

    /* Encapsulating JSONP functions */
    const jsonp = function jsonp(url, config) {
        return new Promise((resolve, reject) => {
            // Initialization parameters
            if (typeof url !== "string") throw new TypeError('url is not a string!');
            if (!isPlainObject(config)) config = {};
            config = Object.assign({
                params: null,
                jsonp: 'callback'
            }, config);

            // Create a global function
            let f_name = `jsonp${+new Date()}`;
            window[f_name] = value => {
                // Request succeeded
                resolve(value);
                delete window[f_name];
                document.body.removeChild(script);
            };

            // Processing URL "splicing question mark Parameter & splicing function name"
            let params = config.params;
            if (params) {
                if (isPlainObject(params)) params = stringify(params);
                url += `${url.includes('?')?'&':'?'}${params}`;
            }
            //Splicing function
            url += `${url.includes('?')?'&':'?'}${config.jsonp}=${f_name}`;

            // Send request
            let script = document.createElement('script');
            script.src = url;
            script.onerror = err => {
                // request was aborted
                reject(err);
            };
            document.body.appendChild(script);
        });
    };

    /* Exposure API */
    if (typeof module === "object" && typeof module.exports === "object") module.exports = jsonp;
    if (typeof window !== "undefined") window.jsonp = jsonp;
})();

call

    <script>
        jsonp('https://www.baidu.com/sugrec', {
            //Question mark parameter value & & keyword
            params: {
                prod: 'pc',
                wd: 'Zhou Dongyu'
            },
            jsonp: 'cb'//The default passed function name is callback
        }).then(value => {
            console.log(value);
        });
    </script>

III CORS

CORS cross domain resource sharing: as long as the server side sets the allowed source, the client is allowed to send requests. In this way, the security policy of the browser can be ignored. The client does not need to do anything. At most one resource credential is configured to be allowed to carry

  • Server settings access control allow origin "
  • Set to *: allow all original access (insecure), and do not allow resource credentials (such as cooike). Access control allow credentials "must be false
  • No * sign is set. Only a single source can be set, but resource vouchers can be carried
  • When a client sends a request to the server, it usually has orgin and referer to record the client's protocol, domain name and port number. The server sets a white list according to the fields

Quad proxy

Proxy cross domain proxy: uses the back-end and back-end communication. By default, there are no security policy restrictions

The intermediate proxy server previews the web page and helps us obtain resources from other servers

Development environment node JS, Vue react = = > webpack dev server

nginx reverse proxy in generation environment

code

  devServer: {
        proxy: {
            '/': {
                target: 'http://127.0.0.1:9999',
                changeOrigin: true
            }
        }
    }

 

Topics: Javascript Front-end Ajax