AJAX in Jquery
First, create a new case client.html, which uses bootstrap for style beautification.
<!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>Jquery send out AJAX request</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> </head> <body> <div cLass="container"> <h2 class="page-header">jQuery send out AJAX request</h2> <button class="btn btn-primary">GET</button> <button class="btn btn-danger">POST</button> <button class="btn btn-info">General method AJAX</button> </div> <script> </script> </body> </html>
The effect of the web page is as follows
Then introduce JQury and enter BootCDN in the web page.
Search jquery and copy the tag.
Then introduce it into the code.
Modify the code in server.js and add the routing rules of jquery.
//1. Introduce express const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules //Request is the encapsulation of request message //Response is the encapsulation of response message // app.get('/server', (request, response) => { // //Set the response header. The name of the header is access control allow origin // //The purpose is to set cross domain permission // response.setHeader('Access-Control-Allow-Origin', '*'); // //Set response body // response.send('HELLO AJAX'); // }); //Change app.post to app.all, which means that any form of request can be accepted. app.all('/server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); response.send(str); }); //Response delay effect app.all('/yanshi', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); //Delay 3 seconds setTimeout(() => { response.send(str); }, 3000) }); //Jquery service app.get('/Jquery', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request response.send('hello jqery') }); app.post('/Jquery', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou' } //Set the response body. send must be a string type, so it needs to convert data response.send(JSON.stringify(data)); }); //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
client.html 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>Jquery send out AJAX request</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- introduce jquery --> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <div cLass="container"> <h2 class="page-header">jQuery send out AJAX request</h2> <button class="btn btn-primary">GET</button> <button class="btn btn-danger">POST</button> <button class="btn btn-info">General method AJAX</button> </div> <script> //Bind event to button $('button').eq(0).click(function () { // The first parameter in get brackets is to whom to send it, the second is to pass some parameters, and the third is a callback function, which can perform some operations on data, such as printing. $.get('http://127.0.0.1:8000/Jquery', { a: 100, b: 200 }, function (data) { console.log(data); }) }) //eq is the query selector. Select the No. button to bind $('button').eq(1).click(function () { // The first parameter in get brackets is to whom to send it, the second is to pass some parameters, and the third is a callback function, which can perform some operations on data, such as printing. //There is also a fourth parameter in parentheses, such as json, which specifies that the data type of the response body is json format $.post('http://127.0.0.1:8000/Jquery', { a: 100, b: 200 }, function (data) { console.log(data); },'json'); }) </script> </body> </html>
The final effect is that clicking GET is an ordinary request, and clicking POST is a request in JSON format.
The Jquery generic method sends AJAX requests
Using this method to send a request is convenient to control various parameters in the request, such as header information, return result type and so on.
<!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>Jquery send out AJAX request</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- introduce jquery --> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <div cLass="container"> <h2 class="page-header">jQuery send out AJAX request</h2> <button class="btn btn-primary">GET</button> <button class="btn btn-danger">POST</button> <button class="btn btn-info">General method AJAX</button> </div> <script> //Bind event to button $('button').eq(0).click(function () { // The first parameter in get brackets is to whom to send it, the second is to pass some parameters, and the third is a callback function, which can perform some operations on data, such as printing. $.get('http://127.0.0.1:8000/Jquery', { a: 100, b: 200 }, function (data) { console.log(data); }) }) //eq is the query selector. Select the No. button to bind $('button').eq(1).click(function () { // The first parameter in get brackets is to whom to send it, the second is to pass some parameters, and the third is a callback function, which can perform some operations on data, such as printing. //There is also a fourth parameter in parentheses, such as json, which specifies that the data type of the response body is json format $.post('http://127.0.0.1:8000/Jquery', { a: 100, b: 200 }, function (data) { console.log(data); }, 'json'); }) // //General method to send Ajax and get requests // $('button').eq(2).click(function () { // $.ajax({ // url: 'http://127.0.0.1:8000/Jquery', // //Parameters // data: { a: 100, b: 200 }, // //Request type // type: 'GET', // //Successful callback function // success: function (data) { // console.log(data); // } // }) // }) //General method to send Ajax and post requests $('button').eq(2).click(function () { $.ajax({ url: 'http://127.0.0.1:8000/Jquery-server', //parameter data: { a: 100, b: 200 }, //Request type type: 'POST', //Responder structure type dataType:'json', //Successful callback function success: function (data) { console.log(data); } }) }) </script> </body> </html>
axios sends AJAX requests
Enter < script SRC=“ https://unpkg.com/axios/dist/axios.min.js "> < / script > introduce online Axios.
<!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>axios send out AJAX request</title> <!-- Introduction of Online axios --> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <button>GET</button> <button>POST</button> <button>AJAX</button> <script> //Get all button buttons const btns = document.querySelectorAll('button'); //Click event GET request for button 1 btns[0].onclick = function () { axios.get('http://127.0.0.1:8000/axios', { //Add some URL parameters params: { id: 100, vip: 7 }, //Set request header information headers: { name: 'zhangsan', age: 20 } //The thing returned from printing is an object containing many properties }).then(value => { console.log(value); }) } //Click event POST request for button 2 btns[1].onclick = function () { axios.post('http://127.0.0.1:8000/axios', { //Add some URL parameters params: { id: 200, vip: 80 }, //Set request header information headers: { name: 'lisi', age: 20 }, //The thing returned from printing is an object containing many properties }).then(value => { console.log(value); }) } //The click event of button 3 sends an AJAX request btns[2].onclick = function () { axios({ //Request method method: 'POST', url: 'http://127.0.0.1:8000/axios', //url parameter params: { vip: 10, level: 30, }, //Header information headers: { a: 200, b: 300 } }).then(response => { console.log(response) }); } </script> </body> </html>
Code in server.js
//1. Introduce express const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules //Request is the encapsulation of request message //Response is the encapsulation of response message // app.get('/server', (request, response) => { // //Set the response header. The name of the header is access control allow origin // //The purpose is to set cross domain permission // response.setHeader('Access-Control-Allow-Origin', '*'); // //Set response body // response.send('HELLO AJAX'); // }); //Change app.post to app.all, which means that any form of request can be accepted. app.all('/server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); response.send(str); }); //Response delay effect app.all('/yanshi', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); //Delay 3 seconds setTimeout(() => { response.send(str); }, 3000) }); //axios services app.all('/axios', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request response.send('hello axios') }); app.post('/axios-server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou' } //Set the response body. send must be a string type, so it needs to convert data response.send(JSON.stringify(data)); }); //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
The implementation results are as follows. There are three request modes, which demonstrate what the codes of different request modes are.
Send AJAX requests using the fetch function
fetch() is an upgraded version of XMLHttpRequest, which is used to issue HTTP requests in JavaScript scripts.
The function of fetch() is basically the same as that of XMLHttpRequest, but there are three main differences.
(1) fetch() uses Promise instead of callback function, which greatly simplifies the writing method and makes it more concise.
(2) fetch() adopts modular design, and the API is distributed on multiple objects (Response object, Request object and Headers object), which is more reasonable; In contrast, the API design of XMLHttpRequest is not very good. The input, output and state are managed in the same interface, so it is easy to write very chaotic code.
(3) fetch() processes data through the data Stream (Stream object) and can be read in blocks, which is conducive to improving the performance of the website and reducing memory consumption. It is very useful for requesting large files or scenes with slow network speed. The XMLHTTPRequest object does not support data flow. All data must be placed in the cache. It does not support block reading. You must wait for all data to be obtained and spit it out at one time.
fetch.html 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>fetch send out AJAX request</title> </head> <body> <button>AJAX request</button> <script> const btn = document.querySelector('button'); btn.onclick = function () { //The first parameter in parentheses is the address, and the second parameter is some configurable objects fetch('http://127.0.0.1:8000/fetch', { //Request method method: 'POST', //Request header headers: { name: 'hahaha' }, //Request body body: 'username=admin&password=admin' }).then(response => { //The returned data is processed into json format return response.json() }).then(response => { console.log(response); }) } </script> </body> </html>
server.js code
//1. Introduce express const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules //Request is the encapsulation of request message //Response is the encapsulation of response message // app.get('/server', (request, response) => { // //Set the response header. The name of the header is access control allow origin // //The purpose is to set cross domain permission // response.setHeader('Access-Control-Allow-Origin', '*'); // //Set response body // response.send('HELLO AJAX'); // }); //Change app.post to app.all, which means that any form of request can be accepted. app.all('/server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); response.send(str); }); //Response delay effect app.all('/yanshi', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); //Delay 3 seconds setTimeout(() => { response.send(str); }, 3000) }); //axios services app.all('/axios', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request response.send('hello axios') }); app.post('/axios-server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou' } //Set the response body. send must be a string type, so it needs to convert data response.send(JSON.stringify(data)); }); //fetch service app.all('/fetch', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request const data = { address: 'Guangzhou' } response.send(JSON.stringify(data)) }); //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
Homology strategy
The same origin policy, first proposed by Netscape, is a security policy for browsers. For example, the URL on the client side is the same as that on the server side:
- The protocol, domain name and port number must be identical.
- Violating the homology policy is cross domain.
- AJAX follows the same origin policy by default.
Solve cross domain, JSONP
The following is a demonstration using a specific case. The new folder is as follows
Demonstrate that the script tag has cross domain capabilities. First, run with < script SRC = ". / JS / APP. JS" > < / script >, and find that the console outputs some data. Here, the URL of the client is not HTTP protocol. Then, in vs code, we use live server to open the web page and obtain the URL after HTTP protocol conversion. When using script tag, we find that the console output does not change.
Principle.html 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>JSONP Principle demonstration</title> </head> <body> <!-- <script src="./js/app.js"></script> --> <!-- adopt live server Obtained by plug-in http Protocol address URL --> <script src="http://127.0.0.1:5500/%E4%BB%A3%E7%A0%81/JSONP/%E5%8E%9F%E7%90%86.html"></script> </body> </html>
app.js code
const data = { name: 'Zhang San' }; console.log(data);
When the script tag is used to request data from the server, the returned statements in server.js should be JS statements and cannot directly return a value.
Principle.html 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>JSONP Principle demonstration</title> </head> <body> <!-- <script src="./js/app.js"></script> --> <!-- adopt live server Obtained by plug-in http Protocol address URL --> <!-- <script src="http://127.0.0.1:5500/%E4%BB%A3%E7%A0%81/JSONP/%E5%8E%9F%E7%90%86.html"></script> --> <script src="http://127.0.0.1:8000/jsonp-server"></script> </body> </html>
server.js error demonstration code
//1. Introduce express const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules //Request is the encapsulation of request message //Response is the encapsulation of response message // app.get('/server', (request, response) => { // //Set the response header. The name of the header is access control allow origin // //The purpose is to set cross domain permission // response.setHeader('Access-Control-Allow-Origin', '*'); // //Set response body // response.send('HELLO AJAX'); // }); //Change app.post to app.all, which means that any form of request can be accepted. app.all('/server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); response.send(str); }); //Response delay effect app.all('/yanshi', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); //Delay 3 seconds setTimeout(() => { response.send(str); }, 3000) }); //axios services app.all('/axios', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request response.send('hello axios') }); app.post('/axios-server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou' } //Set the response body. send must be a string type, so it needs to convert data response.send(JSON.stringify(data)); }); //fetch service app.all('/fetch', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request const data = { address: 'Guangzhou'`Insert the code slice here` } response.send(JSON.stringify(data)) }); //jsonp service app.all('/jsonp-server', (request, response) => { const data = { name: 'Zhang San' }; //Return request response.send('hello jsonp') }) //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
Finally, the browser will report an error, that is, the script cannot directly parse the data.
When we modify the code in server.js
//1. Introduce express const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules //Request is the encapsulation of request message //Response is the encapsulation of response message // app.get('/server', (request, response) => { // //Set the response header. The name of the header is access control allow origin // //The purpose is to set cross domain permission // response.setHeader('Access-Control-Allow-Origin', '*'); // //Set response body // response.send('HELLO AJAX'); // }); //Change app.post to app.all, which means that any form of request can be accepted. app.all('/server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); response.send(str); }); //Response delay effect app.all('/yanshi', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); //Delay 3 seconds setTimeout(() => { response.send(str); }, 3000) }); //axios services app.all('/axios', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request response.send('hello axios') }); app.post('/axios-server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou' } //Set the response body. send must be a string type, so it needs to convert data response.send(JSON.stringify(data)); }); //fetch service app.all('/fetch', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request const data = { address: 'Guangzhou' } response.send(JSON.stringify(data)) }); //jsonp service app.all('/jsonp-server', (request, response) => { const data = { name: 'Zhang San' }; //Return request response.send('console.log("hello jsonp")') }) //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
After correction, the returned is a js expression. It is found that it can be output normally.
Now try using the script tag to get the JSON data on server.js and display it. It can be understood as calling external js.
//1. Introduce express const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules //Request is the encapsulation of request message //Response is the encapsulation of response message // app.get('/server', (request, response) => { // //Set the response header. The name of the header is access control allow origin // //The purpose is to set cross domain permission // response.setHeader('Access-Control-Allow-Origin', '*'); // //Set response body // response.send('HELLO AJAX'); // }); //Change app.post to app.all, which means that any form of request can be accepted. app.all('/server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); response.send(str); }); //Response delay effect app.all('/yanshi', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou 2' } //Set the response body. send must be a string type, so it needs to convert data let str = JSON.stringify(data); //Delay 3 seconds setTimeout(() => { response.send(str); }, 3000) }); //axios services app.all('/axios', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request response.send('hello axios') }); app.post('/axios-server', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Respond to a data and send it to the client const data = { address: 'Guangzhou' } //Set the response body. send must be a string type, so it needs to convert data response.send(JSON.stringify(data)); }); //fetch service app.all('/fetch', (request, response) => { //Set the response header. The name of the header is access control allow origin //The purpose is to set cross domain permission response.setHeader('Access-Control-Allow-Origin', '*'); //The function is to set and run custom request headers response.setHeader('Access-Control-Allow-Headers', '*'); //Return request const data = { address: 'Guangzhou' } response.send(JSON.stringify(data)) }); //jsonp service app.all('/jsonp-server', (request, response) => { const data = { name: 'Zhang San' }; //Return request let str = JSON.stringify(data); response.end(`handle(${str})`) }) //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
<!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>JSONP Principle demonstration</title> <style> #result { width: 100px; height: 200px; border: solid 1px #666; } </style> </head> <body> <div id="result"></div> <script> //Processing returned data function handle(data) { const result = document.getElementById('result'); result.innerHTML = data.name } </script> <!-- <script src="./js/app.js"></script> --> <!-- adopt live server Obtained by plug-in http Protocol address URL --> <!-- <script src="http://127.0.0.1:5500/%E4%BB%A3%E7%A0%81/JSONP/%E5%8E%9F%E7%90%86.html"></script> --> <script src="http://127.0.0.1:8000/jsonp-server"></script> </body> </html>
The final output effect is as follows
Cross domain request CORS response
Set up such a case.
The cors.html code is as follows
<!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>cors</title> <style> #result { width: 200px; height: 100px; border: solid 1px #90b; } </style> </head> <body> <button>Send request</button> <div id="result"></div> <script> const btn = document.querySelector('button'); btn.onclick = function () { const result = document.getElementById('result'); //1. Create object const x = new XMLHttpRequest(); //2. Initialization settings x.open("GET", "http://127.0.0.1:8000/cors-server"); //3. Send x.send(); //4. Bind event processing response results x.onreadystatechange = function () { if (x.readyState === 4) { if (x.status >= 200 && x.status < 300) { //Output response body console.log(x.response); result.innerHTML = x.response } } } } </script> </script> </body> </html>
The server.js code is as follows
//1. Introduce express const { response } = require('express'); const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules app.all('/cors-server', (request, response) => { //Respond directly here response.send('hello cors') }) //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
The output error is the problem of the request header.
Our client is the file protocol, which sends requests to the server-side HTTP protocol. Belongs to cross domain request
Therefore, it needs to be processed in the server-side code server.js. Added the setting of cross domain response header
//1. Introduce express const { response } = require('express'); const express = require('express'); //2. Create application object const app = express(); //3. Create routing rules app.all('/cors-server', (request, response) => { //Set response header response.setHeader("Access-Control-Allow-Origin", "*") //If you only want an interface to have the response header, you can replace the * sign with the http address //Respond directly here response.send('hello cors') }) //4. Listening port start service //The listening port is 8000, followed by a callback function app.listen(8000, () => { console.log("The service has been started. Port 8000 is listening..."); })
The final results are as follows: the cross domain request is successfully implemented.