In-depth analysis of homology and cross-domain, jsonp (function encapsulation), CORS principle

In-depth analysis of homology and cross-domain, jsonp (function encapsulation), CORS principle

Same Origin Policy

Ajax request limits:

Ajax can only send requests to its own server

The same-origin policy is a security feature of the browser. Client scripts from different origins cannot read or write each other's resources without explicit authorization.

For example, there is a website A and a website B. The HTML file in website A can only send Ajax requests to the server of website A.

The HTML file in website B only sends Ajax requests to website B, but website A cannot send Ajax requests to website B.

Similarly, website B cannot send Ajax requests to website A.

Homologous:

If two pages have the same protocol, domain name, and port, then the two pages belong to the same source. If just one of them is different, they are from different sources.

http://www.example.com/dir/page.html

  • http://www.example.com/dir2/other.html: Same origin
  • http://example.com/dir/other.html: different origin (different domain name)
  • http://v2.www.example.com/dir/other.html: different origin (different domain name)
  • http://www.example.com:81/dir/other.html: different source (different port)
  • https://www.example.com/dir/page.html: Different origin (different protocol)

Purpose of the Same Origin Policy:

  • The same-origin policy is designed to ensure the security of user information and prevent malicious websites from stealing data. The original same-origin policy means that the cookies set by website A on the client cannot be accessed by website B.
  • With the development of the Internet, the same-origin policy has become more and more stringent. In the case of different sources, one of the regulations is that Ajax requests cannot be sent to non-same-origin addresses. If a request is made, the browser will report an error.

Not restricted by the same-origin policy:

Links, redirects, and form submissions in pages are not subject to the same-origin policy, and the introduction of cross-domain resources is allowed. But js cannot read and write the loaded content. Such as <script src="..."></script> , <img> , <link> , <iframe> , etc. embedded in the page

Cross-domain issues

Cross-domain: As long as there is a difference in the protocol, domain name, or port number, it is cross-domain

Cross-domain reasons:

The cross-domain problem comes from JavaScript's same-origin policy, which means that only when the protocol + host name + port number (if any) are the same, mutual access is allowed.

In order to prevent the interface under a certain domain name from being illegally called by web pages under other domain names, the browser imposes security restrictions on JavaScript.

That is to say, JavaScript can only access and operate resources under its own domain, and cannot access and operate resources under other domains.

The cross-domain problem is for JS and Ajax, HTML itself does not have cross-domain issues.

For example, a tag, script tag, and even form tag (which can directly send and receive data across domains) etc.

Solve cross-domain issues:

JSONP : Using the cross-domain feature of the script tag, the function of the current script can be directly called back in the cross-domain script.

CORS : The server sets the Access-Control-Allow-Origin value in the HTTP response header to remove cross-domain restrictions. Note: Both of these cross-domain solutions have a fatal flaw and rely heavily on backend assistance.

Reverse Proxy Proxy: A cross-domain solution that can be solved independently by the front end:

Refers to using a proxy server to accept connection requests on the Internet.

The request is then forwarded to a server on the internal network.

And return the results obtained from the server to the client requesting the connection on the Internet.

At this point, the proxy server appears to the outside world as a reverse proxy server.

JSONP

Solved with JSONP

jsonp is an abbreviation for JSON with padding. It does not belong to Ajax requests, but it can simulate Ajax requests.

JSONP consists of two parts: callback function and data

  • The callback function is the function that should be called in the page when the response comes. The name of the callback function is usually specified in the request.
  • data is the JSON data passed into the callback function.

Solution:

Simple understanding: On the server side, the json data is used as a function parameter, filled into the function, and the function is called on the client to process the data

insert image description here

The principle of JSONP to implement cross-domain requests is simply to dynamically create a <script> tag, and then use the src of <script> to obtain data across domains without being constrained by the same-origin policy.

Advantages and disadvantages of JSONP:

advantage:

Unlike Ajax requests implemented by the XMLHttpRequest object, which are restricted by the same-origin policy, it has better compatibility and can run in older browsers.

It does not require XMLHttpRequest or ActiveX support and can return the result by calling callback after the request is completed.

shortcoming:

Only GET requests are supported, but other types of HTTP requests such as POST are not supported. Only cross-domain HTTP requests are supported.

It does not solve the problem of how to make JavaScript calls between two pages on different domains

JSONP code optimization:

The client needs to pass the function name to the server

Transform script requests into dynamic requests

Encapsulate jsonp function to facilitate request sending

Server-side code optimization res.jsonp method

JSONP function encapsulation:

function jsonp (options) {
    // Dynamically create script tag var script = document.createElement('script');
    // Variable for concatenating strings var params = '';
    for (var attr in options.data) {
        params += '&' + attr + '=' + options.data[attr];
    }
    //myJsonp0124741
    var fnName = 'myJsonp' + Math.random().toString().replace('.', '');
    // Make it a global function window[fnName] = options.success;
    // Add src attribute to script tag script.src = options.url + '?callback=' + fnName + params;
    // Append the script tag to the page document.body.appendChild(script);
    // Add onload event to script tag script.onload = function () {
        document.body.removeChild(script);
    }
}

use:

// Get the button var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
// Add a click event to the button btn1.onclick = function () {
    jsonp({
        // Request address url: 'http://localhost:3001/better',
        data: {
            name: 'lisi',
            age: 30
        },
        success: function (data) {
            console.log(123)
            console.log(data)
        }
    })
}
btn2.onclick = function () {
    jsonp({
        // Request address url: 'http://localhost:3001/better',
        success: function (data) {
            console.log(456789)
            console.log(data)
        }
    })
}

CORS

Solve with CORS

CORS: The full name is Cross-origin resource sharing, which allows browsers to send Ajax requests to cross-domain servers, overcoming the limitation that Ajax can only be used with the same origin.

insert image description here

//Set the server's response header information to achieve cross-domain res.setHeader("Access-Control-Allow-Origin", "*"); /* The asterisk indicates that all domains are acceptable, */

Cross-domain implementation in Express framework:

Install the cross-domain module: Syntax: npm install cors

Import the cors module in the app.js file: var cors = require('cors')

Use the cross-domain module (in the app.js file): app.use(cors())

The above is a detailed analysis of the same-origin and cross-domain, jsonp (function encapsulation), and CORS principles. For more information about same-origin and cross-domain, jsonp (function encapsulation), and CORS, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Implementation of JSONP to solve JS cross-domain problem
  • Analysis of the Principle of Jsonp Cross-Domain Solution
  • jQuery uses jsonp to implement Baidu search sample code
  • Baidu search box smart prompt case jsonp
  • JSONP cross-domain simulation Baidu search

<<:  Gearman + MySQL to achieve persistence operation example

>>:  Detailed graphic tutorial on installing Ubuntu 20.04 dual system on Windows 10

Recommend

Div nested html without iframe

Recently, when doing homework, I needed to nest a ...

Summary of some problems encountered when integrating echarts with vue.js

Preface I'm currently working on the data ana...

How to clear the validation prompt in element form validation

Table of contents Problem scenario: Solution: 1. ...

How to install ionCube extension using pagoda

1. First install the pagoda Installation requirem...

How to match the size of text in web design: small text, big experience

With the rise of mobile terminals such as iPad, p...

Docker installs Redis and introduces the visual client for operation

1 Introduction Redis is a high-performance NoSQL ...

How to deploy a simple c/c++ program using docker

1. First, create a hello-world.cpp file The progr...

Detailed tutorial on configuring local yum source in CentOS8

The centos8 distribution is released through the ...

Join operation in Mysql

Types of joins 1. Inner join: The fields in the t...

Causes and solutions for cross-domain issues in Ajax requests

Table of contents 1. How is cross-domain formed? ...

Summary of Linux ps and pstree command knowledge points

The ps command in Linux is the abbreviation of Pr...