Same Origin Policy for Ajax Cross-Domain Requests, Cross-Domain Requests & jsonp Principles for Realizing Cross-Domain Requests, jQuery Realizing Cross-Domain Requests, CORS Cross-Domain & XML Format - Obsolete & Ajax Requests Follow the HTTP Protocol

Same Origin Policy for Ajax Cross-Domain Requests, Cross-Domain Requests & jsonp Principles for Realizing Cross-Domain Requests, jQuery Realizing Cross-Domain Requests, CORS Cross-Domain & XML Format - Obsolete & Ajax Requests Follow the HTTP Protocol

3. Ajax cross domain request

3.1 Same Origin Policy

In 1995, the Same Origin Policy was introduced to browsers by Netscape. Currently, all browsers enforce this policy.

Originally, it meant that the cookie set by website A cannot be opened by website B unless the two web pages have the same origin. The so-called homology refers to three identical.

  • Same protocol (http https)
  • same domain name
  • The ports are the same (http defaults to port 80, https defaults to port 443)

insert image description here

With the development of the Internet, the same-origin policy has become more and more strict. Currently, there are three behaviors that are restricted if non-homologous.

  • Cookie could not be read.
  • DOM could not be obtained.
  • Invalid AJAX request(can be sent, but the browser will refuse to accept the response).

3.2 What is a cross-domain request

In fact, if you understand what the same-origin policy is, you will know what a cross-domain request is.

When sending an Ajax request, as long as the requested address violates the same-origin policy, it is a cross-domain request.

3.3 A solution for implementing cross-domain requests – JSONP

1) Introduction to JSONP

JSON with P adding is a technique for sending cross-domain requests with the help of scripttags .

The principle is that the client uses scriptthe tag to request an address of the server, and the address of the server returns a JavaScript script (not a piece of HTML) with a global function call, and passes the data that needs to be returned to the client to the client through parameters. In this function, the data that the original server wants to return can be obtained in the function.

In most cases in the future, JSONP will be used to complete cross-domain requests between different source addresses

2) Use JSONP to implement cross-domain requests

  1. First, two servers must be created, one server (:3000) sends a request to the other server (:4000)

insert image description here
insert image description here

  1. Write an HTML page index.html in 3000

  2. Inside 3000, in app.js, return index.html

    app.get('/index.html', (req, res) => {
          
          
        res.sendFile(__dirname + '/index.html');
    })
    

    Restart the server, at this time, you can see the page by visiting 127.0.0.1:3000/index.html

  3. In the index.html in 3000, through the src attribute of the script, request an interface in the 4000 website

    <script src="http://127.0.0.1:4000/getHeroes"></script>
    
  4. To 4000, write the interface getHeroes, complete the response

    app.get('/getHeroes', (req, res) => {
          
          
        // 返回的内容,只要符合JS的语法即可
        // res.send('hello');
        res.send('alert(123)');
    })
    

    After writing, 4000 to restart the server

  5. Refresh the page to see the pop-up box

    <script src="http://127.0.0.1:4000/getHeroes"></script>
    

3) Realize cross-domain data transfer

The cross-domain request was implemented earlier. If the 4000 website returns a string to call a function, then the 3000 website will also execute a function after receiving it. Then pass a parameter to the function, which is the data to be transmitted.

  1. 4000 sites, returns a string that calls the function

    app.get('/getHeroes', (req, res) => {
          
          
        // res.send('hello');
        // res.send('alert(1234);');
    
        let heroes = [
            {
          
          name: '曹操', age: 30},
            {
          
          name: '鲁达', age: 31}
        ];
        heroes = JSON.stringify(heroes);
    
        res.send('abc('+heroes+')');
    });
    
  2. 3000 sites, toin advancePrepare a function called abc to receive the data returned by 4000

    <script>
        // 输出4000网站返回的内容
        // console.log(aa);
    
        // 为了配合4000网站的要求,所以要定义一个abc函数
        function abcd (res) {
            
            
            console.log(res);
        }
    </script>
    
    <script src="http://127.0.0.1:4000/getHeroes"></script>
    

    In this way, cross-domain requests can be realized. And also realized the transmission of data.

    The question is how to unify the function names of the two websites? Everyone has an agreement that when requesting, you must pass your function name to the 4000 website, and the parameter name must be callback.

  3. In the 3000 website, the function name is passed as a parameter

    <script>
        // 输出4000网站返回的内容
        // console.log(aa);
    
        // 为了配合4000网站的要求,所以要定义一个abc函数
        function abc(res) {
            
            
            console.log(res);
        }
    </script>
    
    <script src="http://127.0.0.1:4000/getHeroes?callback=abc"></script>
    
  4. In the 4000 website, get the callback parameter in the address bar, and the value is the name of the function

    app.get('/getHeroes', (req, res) => {
          
          
        // res.send('hello');
        // res.send('alert(1234);');
    
        let heroes = [
            {
          
          name: '曹操', age: 30},
            {
          
          name: '鲁达', age: 31}
        ];
        heroes = JSON.stringify(heroes);
    
        // 获取函数名
        let fn = req.query.callback;
        // res.send('alert(' + heroes + ')');
        res.send(fn + '('+heroes+')');
    });
    

example

1. Create a new client-side 3000 folder and a server-side 4000 folder, and initialize them

npm init -y
npm i express

2. New app.js

3000/app.js

const express = require('express');
const ap = express();
app.listen(3000, () => console.log('3000 start'));

4000/app.js

const express = require('express')
const app = express()
app.listen(4000, () => console.log('4000 start'))

3. Start the project

node .\app.js

nodemon .\app.js

Effect

insert image description here

4. jsonp code

insert image description here

the code

3000/index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <img src="https://gss3.bdstatic.com/84oSdTum2Q5BphGlnYG/timg?wapp&quality=80&size=b150_150&subsize=20480&cut_x=0&cut_w=0&cut_y=0&cut_h=0&sec=1369815402&srctrace&di=0767d0a97b3985dc375171590995e75e&wh_rate=null&src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fpic%2Fitem%2F562c11dfa9ec8a13467195f0f903918fa0ecc0b3.jpg"
    />
    <script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <!-- JSONP原理代码 -->
    <script>
        // 4000网站返回的内容,被3000网站当做js代码执行了
        function abcd (res) {
      
      
            console.log(res);
        }
    </script>
    <script src="http://127.0.0.1:4000/getHeroes?callback=abcd"></script> 

</body>

</html>

4000/app.js

const express = require('express')
const app = express()
app.listen(4000, () => console.log('4000 start'))

// 定义一个接口
app.get('/getHeroes', (req, res) => {
    
    
  // res.send('hello');
  // res.send('alert(1234);');

  let heroes = [
    {
    
     name: '曹操', age: 30 },
    {
    
     name: '鲁达', age: 31 },
  ]
  heroes = JSON.stringify(heroes)

  // 获取函数名
  let fn = req.query.callback
  // res.send('alert(' + heroes + ')');
  res.send(fn + '(' + heroes + ')')
})

4) The ajax method encapsulated by jQuery cross-domain request

  1. In the 3000 website, a jQuery file is introduced into jsonp2.html. For convenience (introducing your own jQuery, you have to write the code to process static resource files), the jQuery provided by Baidu is introduced.

  2. Use the ajax method provided by jQuery to achieve cross-domain access

    3000/index.html

    <!-- 使用jQuery提供的ajax方法,实现跨域请求 -->
    <!-- 下面引入百度提供的jQuery,需要联网 -->
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    
    <script>
        $.ajax({
            
            
            type: 'GET',
            url: 'http://127.0.0.1:4000/getHeroes',
            dataType: 'jsonp',  / 这里一定要使用jsonp
            success: function (res) {
            
            
                console.log(res)
            }
        });
    </script>
    

    4000/app.js file unchanged, same as above

    3000/index.htmlComplete code

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    
    <body>
        <img src="https://gss3.bdstatic.com/84oSdTum2Q5BphGlnYG/timg?wapp&quality=80&size=b150_150&subsize=20480&cut_x=0&cut_w=0&cut_y=0&cut_h=0&sec=1369815402&srctrace&di=0767d0a97b3985dc375171590995e75e&wh_rate=null&src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fpic%2Fitem%2F562c11dfa9ec8a13467195f0f903918fa0ecc0b3.jpg"
        />
        <script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
        <script>
            $.ajax({
            
            
                type: 'GET',
                url: 'http://127.0.0.1:4000/getHeroes',
                dataType: 'jsonp',
                success: function(res) {
            
            
                    console.log(res)
                }
            });
        </script>
    
        <!-- JSONP原理代码 -->
        <!-- <script>
            // 4000网站返回的内容,被3000网站当做js代码执行了
            function abcd (res) {
                console.log(res);
            }
        </script>
        <script src="http://127.0.0.1:4000/getHeroes?callback=abcd"></script> -->
    
    </body>
    
    </html>
    

    Open the page effect

insert image description here

3.4 Implementation of cross-domain request scheme - CORS

by **quilt**Setting the header in the route of the request can achieve cross-domain. However, this method is only supported by the latest browser (IE10).

Cross Origin Resource Share, cross-domain resource sharing

app.get('/time', (req, res) => {
    
    
  // // 允许任意源访问,不安全
  // res.setHeader('Access-Control-Allow-Origin', '*')
  // 允许指定源访问
  res.setHeader('Access-Control-Allow-Origin', 'http://www.xxx.com')
  res.send(Date.now().toString())
})

This solution does not require the client to make any changes (the client does not need to change the code), but only adds Access-Control-Allow-Origina , indicating whether the resource allows the specified domain request.

example

cors effect

insert image description here

code-cors code

insert image description here

the code

3000 client serial code

3000/app.js

const express = require('express');
const app = express();
app.listen(3000, () => console.log('3000 start'));

// 显示index.html
app.get('/index.html', (req, res) => {
    
    
    res.sendFile(__dirname + '/index.html');
});

app.get('/cors.html', (req, res) => {
    
    
    res.sendFile(__dirname + '/cors.html');
});

3000/index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <img src="https://gss3.bdstatic.com/84oSdTum2Q5BphGlnYG/timg?wapp&quality=80&size=b150_150&subsize=20480&cut_x=0&cut_w=0&cut_y=0&cut_h=0&sec=1369815402&srctrace&di=0767d0a97b3985dc375171590995e75e&wh_rate=null&src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fpic%2Fitem%2F562c11dfa9ec8a13467195f0f903918fa0ecc0b3.jpg"
    />
    <script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $.ajax({
      
      
            type: 'GET',
            url: 'http://127.0.0.1:4000/getHeroes',
            dataType: 'jsonp',
            success: function(res) {
      
      
                console.log(res)
            }
        });
    </script>

    <!-- JSONP原理代码 -->
    <!-- <script>
        // 4000网站返回的内容,被3000网站当做js代码执行了
        function abcd (res) {
            console.log(res);
        }
    </script>
    <script src="http://127.0.0.1:4000/getHeroes?callback=abcd"></script> -->

</body>

</html>

3000/cors.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://127.0.0.1:4000/aa');
        xhr.send();
        xhr.onload = function () {
      
      
            console.log(this.response)
        }
    </script>
</body>
</html>
4000 server serial code

4000/app.js

const express = require('express')
const app = express()
app.listen(4000, () => console.log('4000 start'))

// 定义一个接口
app.get('/getHeroes', (req, res) => {
    
    
  // res.send('hello');
  // res.send('alert(1234);');

  let heroes = [
    {
    
     name: '曹操', age: 30 },
    {
    
     name: '鲁达', age: 31 },
  ]
  heroes = JSON.stringify(heroes)

  // 获取函数名
  let fn = req.query.callback
  // res.send('alert(' + heroes + ')');
  res.send(fn + '(' + heroes + ')')
})

// 实现CORS跨域的接口
app.get('/aa', (req, res) => {
    
    
  // 加入CORS头
  // res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:3000')
  res.end('hello')
})

4.XML

HTML: Hypertext Markup Language

XML:eXtension MsheetLlanguage eXtensible Markup Language

A means of data description

Let’s briefly demonstrate the old-fashioned things, don’t waste time here, basically the current projects don’t need it.

Reason for elimination: Too much data redundancy

<?xml version="1.0" encoding="UTF-8" ?>
<students>
	<stu id="1">
    	<name>张三</name>
        <age>18</age>
        <sex></sex>
        <other height="175cm" weight="65kg" />
    </stu>
    <stu id="2">
    	<name>李四</name>
        <age>20</age>
        <sex></sex>
        <other height="170cm" weight="60kg" />
    </stu>
</students>

XML syntax specification:

  • Similar to html writing
  • has one and only one root tag
  • Labels are case sensitive
  • label must be closed
  • Attribute values ​​must be quoted

If the server returns data in XML format, after JS receives the data, it can process the received data as a document object

5. Native xhr obtains the information of the request message and the response message

Ajax requests also follow the http protocol.

During the ajax request process, you can set the request message or get the response message

<script>
    // 请求报文:
    // 行
    // 头
    // 体
    // 响应报文:
    // 行
    // 头
    // 体
    var xhr = new XMLHttpRequest();
    xhr.open('post', '/abc'); // 体现了请求行的内容(请求方式和接口地址)
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 体现了请求头
    xhr.send('aa=xxx&bb=yyy'); // 体现了请求体
    xhr.onload = function () {
      
      
        console.log(this.status); // 体现了响应行的状态码
        console.log(this.statusText); // 体现了响应行的状态描述信息
        console.log(this.getAllResponseHeaders()); // 体现了所有的响应头
        console.log(this.getResponseHeader('content-length')); // 体现了所有的响应头
        console.log(this.response); // 体现了响应体的内容
    }
</script>

example

1. Create a new http folder and initialize it

npm init -y
npm i express

2. Build a server

http/app.js

const express = require('express');
const app = express();

app.listen(3000, () => console.log('kaiqi'));

app.get('/index.html', (req, res) => {
    
    
    res.sendFile(__dirname + '/index.html');
});

app.post('/abc', (req, res) => {
    
    
    res.send('hello');
});

3. Visit the page

http/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        // 请求报文:
            // 行
            // 头
            // 体
        // 响应报文:
            // 行
            // 头
            // 体
        var xhr = new XMLHttpRequest();
        xhr.open('post', '/abc'); // 体现了请求行的内容(请求方式和接口地址)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 体现了请求头
        xhr.send('aa=xxx&bb=yyy'); // 体现了请求体
        xhr.onload = function () {
      
      
            console.log(this.status); // 体现了响应行的状态码
            console.log(this.statusText); // 体现了响应行的状态描述信息
            console.log(this.getAllResponseHeaders()); // 体现了所有的响应头
            console.log(this.getResponseHeader('content-length')); // 体现了所有的响应头
            console.log(this.response); // 体现了响应体的内容
        }
    </script>
</body>
</html>

4. In the http terminal, start the service

node ./app.js

5. Page access, display data

Address - http://127.0.0.1:3000/index.html

6. Effect

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44867717/article/details/130234450