I. Cross-domain
1.1 Introduction
What is a cross-domain call? [Important]
Cross-domain calls occur when the current address is inconsistent with the protocol, host name, port number in the address to be requested, because the browser's homology policy restricts it.
Two ways to resolve cross-domain calls: [Key]
First, set the response header information on the server side that allows cross-domain calls:
res.header('Access-Control-Allow-Origin', '*'); //Turn on allow cross-domain calls res.header('Access-Control-Allow-Methods', '*'); //All request modes allow cross-domain calls
Or use third-party cors middleware to resolve cross-domain calls, code as follows:
// Install cors: NPM I CORS in the project root directory const cors = require('cors'); app.use(cors());
Second: using JSONP technology:
What is JSONP technology? [Key]
JSONP technology belongs to javascript technology, but it is not ajax. The front end uses the SRC attribute in <img src="> label, <script src="></script> label to call the server-side program. When calling the server-side program, a callback function (anonymous function) is passed to the server-side. The server receives and calls the callback function, which is passed to the front-end by calling the callback function.
The disadvantage of JSONP is that only get-mode requests can be sent, not post-mode requests.
The front-end code is as follows:
<script> var fn = function(d) { console.log(d, 6666); } </script> <script src="http://localhost:3000/mydemo?usr=zhangsan&calls=fn"></script>
The service-side code is as follows:
const express = require('express'); const app = express(); app.listen(3000, () => { console.log('3000 port'); }); //Test JSONP: app.get('/mydemo', (req, res) => { let users = req.query.usr ? req.query.usr : ''; let calls = req.query.calls ? req.query.calls : ''; // console.log(users, calls, 9999); if (users == 'zhangsan') { // Res.send ({status: 500, msg:'Account number registered'}); res.send(`${calls}({ status: 500, msg: 'Account number registered' })`); } else { // Res.send ({status: 200, msg:'Account available'}) res.send(`${calls}({ status: 200, msg: 'Account number available ' })`); } });
Cross-domain species
Cross-domain Error [Key]
1.2 CORS Resolution Cross-Domain
1.2.1 Configuring cors
1.2.1.1 Access-Control-Allow-Origin
Grammar:
res.header('Access-Control-Allow-Origin', '*');
Description: By default, ajax requests can only be sent using a domain. This property sets which source (url) can be requested. Often set to *
1.2.1.2 Access-Control-Allow-Methods
Grammar:
res.header('Access-Control-Allow-Methods', '*');
Description: By default, CORS only supports clients making GET, POST requests. If clients want to request server resources through PUT, DELETE, etc., they need to specify the HTTP methods allowed for actual requests on the server side through Access-Control-Alow-Methods.
1.2.2 cors Middleware
(1) Run npm install cors to install the middleware
(2) Import middleware using const cors = require('cors')
(3) Call app.use(cors()) to configure the middleware before routing
1.3 JSONP Resolution Cross-Domain
1.3.1 Principle
JSONP technology belongs to javascript technology, but it is not ajax. The front end uses the SRC attribute in <img src="> label, <script src="></script> label to call the server-side program. When calling the server-side program, a callback function (anonymous function) is passed to the server-side. The server receives and calls the callback function, which is passed to the front-end by calling the callback function.
1.3.2 Features/Disadvantages
The disadvantage of JSONP is that only get-mode requests can be sent, not post-mode requests.
2. Promise and Ajax
2.1 Encapsulate ajax using promise
The common.js file code is as follows:
//Requirements: Encapsulate functions that send ajax requests function sendAjax(url, type = 'get', data = {}, dataType = 'json') { return new Promise((resolve, reject) => { $.ajax({ url, data, type, dataType, success(d) { //Requirements: Return d resolve([true, d]); }, error(e) { resolve([false, e]); } }); }); }
2.2 Send ajax using an encapsulated method
Define the index.html file and use the sendAjax method encapsulated above with the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script> <script src="./1-common.js"></script> <script> //Get the first page broadcast map: async function mytest() { let data = await sendAjax('http://localhost:3000/banner'); console.log(data, 111); } mytest(); </script> </head> <body> </body> </html>