[Ajax] basic use of ajax / cross-domain issues / get and post

Table of contents

1. Overview of Ajax

1.1 Introduction to AJAX

1.2 Introduction to XML

1.3 Features of AJAX

1.3.1 Advantages of AJAX

1.3.2 Disadvantages of AJAX

2. Use of AJAX

2.1 Steps to use

2.2 Complete get request with parameters (handwritten)

2.3 Complete post request with parameters (handwritten)

2.4 Parsing json data

2.5 Continuous writing method of destructuring assignment (supplement)

2.6 IE cache problem (time stamp)

2.7 Exception and timeout handling of ajax requests

2.8 ajax cancel request xhr.abort( )

2.9 Avoid multiple repeated requests

3. jQuery encapsulates Ajax

4. Cross domain

4.1 JSONP solves cross-domain (not required for work, frequently asked in interviews) (handwritten)

4.2 JQuery encapsulates JSONP

4.3 CORS solves cross domain (backend technology)

5. get and post

GET

POST

1. Ajax overview

1.1 Introduction to AJAX

The full name of AJAX is Asynchronous JavaScript And  XML , which is asynchronous JS and XML.

AJAX can send an asynchronous request to the server in the browser, the biggest advantage: get data without refreshing . 

Vernacular: Sometimes you don’t want the page to jitter and jump, and you can refresh the new data without refreshing the page, which is the most commonly used interaction method for the front-end and back-end

AJAX is not a new programming language, but a new way of combining existing standards.

1.2 Introduction to XML

XML  Extensible Markup Language (Extensible Markup Language)

XML was designed to transmit and store data.

XML is similar to HTML, the difference is that HTML has pre-defined tags, while XML has no pre-defined tags, all are custom tags, used to represent some data.

For example, I have a student data:
name = "Monkey King"; age = 18; gender = "male";
expressed in XML:

<student>
	<name>孙悟空</name>
	<age>18</age>
	<gender>男</gender>
</student>

It has now been replaced by JSON:

{"name":"孙悟空","age":18,"gender":"男"}

1.3 Features of AJAX

1.3.1 Advantages of AJAX

① Can communicate with the server without refreshing the page
② Allows you to update part of the page content based on user events

1.3.2 Disadvantages of AJAX

There is no browsing history, no rollback (only one page)
there is a cross-domain problem (same origin)  is very important, how to solve cross-domain
SEO is not friendly (search engines, crawlers cannot crawl ajax updated things)

2. Use of AJAX

2.1 Steps to use

core object

All XMLHttpRequest
AJAX operations are performed through this object

Steps for usage

  1. Initialize the environment, download the express package
# npm init --yes 初始化
# npm i express 安装express

  1. Write js code server.js
// 1. 引入express
const express = require('express');

// 2. 创建应用对象
const app = express();

// 2.1暴露静态资源
app.use(express.static(__dirname+'/src'))
// 3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.get('/test_get', (request, response) => {
  //  设置响应
  console.log("有人请求test_get了");
  response.send("Hello_test_get");
});

// 4. 监听端口,启动服务
app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/1_ajax小试牛刀.html");
 })

  1. run-server.js
node server.js
  1. Install nodemon, you can automatically restart the server
# npm install -g nodemon

start service

# ndoemon server.js

1. Ajax small test. html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta >
    <title>AJAX GET 请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>
    <script>
        //获取button元素
        const btn = document.getElementsByTagName('button')[0];
        const result = document.getElementById('result');
        btn.onclick = function(){
           //1.创建xhr的实例对象
           const xhr = new XMLHttpRequest();
           //2.指定发送请求方法method和url
           xhr.open('GET','http://127.0.0.1:8080/test_get');
           //3.发送请求
           xhr.send();
           //4.事件绑定 处理服务端返回的结果
           // 当 准备 状态 发生变化
           xhr.onreadystatechange = function(){
              /* if(xhr.readyState ===1){
              	xhr.setRequestHeader('demo',123)//配置请求头
              }*/
              /* if(xhr.readyState ===2){
              	xhr.setRequestHeader('demo',123)//配置请求头--报错(send已经调用了,已经无法修改请求头)
              }*/
              /* if(xhr.readyState ===3){
             	 console.log('3时接收到的数据',xhr.response);//小的数据已经回来了
             	 console.log('3时接收到的响应头',xhr.getAllResponseHeaders());//所有响应头
             	 
             }*/
                if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
                    // 处理 行 头 空行 体
                    //响应行
                    // console.log(xhr.status);//http的状态码
                    // console.log(xhr.statusText);//状态字符串
                    // console.log(xhr.getAllResponseHeaders());//所有响应头
                    console.log(xhr.response);//返回的数据
                    //设置result的文本
                    result.innerHTML = xhr.response;
                }
           } 
        }
    </script>
</body>
</html>


readystate is an attribute in the xhr object, there are 5 states 0, 1, 2, 3, 4, and it changes 4 times (just understand)

    0: The moment the instance comes out is 0, the initial state
    1: The server connection has been established, ( open has been called, but send has not been called, and the content of the request header can be modified at this time )
    2: The request has been received ( send has been called, has been The request header cannot be modified )
    3: The request is being processed ( part of the data has been returned, the small data has been accepted at this stage, and the larger data is waiting for further reception )
    4: The request has been completed and the response is ready ( all data has been accepted )

2.2 Complete get request with parameters (handwritten)

server.js

const express = require('express');
const app = express();
app.use(express.static(__dirname+'/src'))
//  响应GET请求 # 
app.get('/test_get', (request, response) => {
  console.log("有人请求test_get了,携带的query参数是:",request.query);
  response.send("Hello_test_get");
});
//  响应GET请求 #2
app.get('/test_get2/:name/:age', (request, response) => {
  console.log("有人请求test_get2了,携带的params参数是:",request.qparams);
  response.send("Hello_test_get2");
});
app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/3_ajax——get请求.html");
 })

3. ajax - get request . html (complete handwriting is required for the interview)

btn.onclick = function(){
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
		 console.log(xhr.response);//返回的数据
	     }
	 }
    /*
    需要掌握(query和params的形式)
     1.形如:key=value&key=value 就是query参数的 urlencoded 编码形式
     2.形如:/xx/xxx/ 老刘/18 就是params参数
    */
    //2.指定发送请求方法method和url
    xhr.open('GET','http://127.0.0.1:8080/test_get?name=老刘&age=18'); //携带query参数,使用urlencoder编码
    //xhr.open('GET','http://127.0.0.1:8080/test_get2/老刘/18'); //携带params参数
    //3.发送请求
    xhr.send();
 }

2.3 Complete post request with parameters (handwritten)

server.js

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

//使用中间件解析urlencoded编码形式的请求体参数
//app.use(express.urlencoded({extended:true}))

//使用中间件解析json编码形式的请求体参数
app.use(express.json())

app.use(express.static(__dirname+'/src'))

// 响应POST请求
/* post方式可以接收query和params参数(但一般不这么用)
  app.post('/test_post/:name/:age',(request,response)=>{
  console.log("有人请求test_post了",request.params);
  response.send("Hello_test_post");
});
*/

//post方式的接收请求体参数
app.post('/test_post/:name/:age',(request,response)=>{
  console.log("有人请求test_post了",request.body);
  response.send("Hello_test_post");
});

app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/4_ajax——post请求.html");
 })

4. ajax—— post request (interview needs to be completely handwritten)

btn.onclick = function(){
    // 1
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
		 console.log(xhr.response);//返回的数据
	     }
	}
   /*  post 可以带query和params参数,但是很少用
	   // 1 xhr.open('POST','http://127.0.0.1:8080/test_post?name=老刘&age=18');
	   // 2 xhr.open('POST','http://127.0.0.1:8080/test_post/老刘/18'); //携带params参数
	   xhr.send();
   */
   // 2 指定发送请求的:method、url、参数
   xhr.open('POST','http://127.0.0.1:8080/test_post')
   
   // 追加请求响应头用于识别携带的请求体参数的编码形式-urlencoded
   // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

   // 追加请求响应头用于识别携带的请求体参数的编码形式-json    
   xhr.setRequestHeader('Content-Type','application/json');
           
   // 3 发送请求
   // 携带urlencoded编码形式的请求体参数
   //xhr.send(name=老刘&age=18);

   // 携带json编码形式的请求体参数
   const person = {name:'老刘',age:18}
   xhr.send(JSON.stringify(person));
 }

2.4 Parsing json data

server.js

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

app.use(express.static(__dirname+'/src'))

//post方式的接收请求体参数
app.get('/get_person',(request,response)=>{
  console.log("有人请求get_person了");
  const person ={name:'老刘',age:18,sex='女'}
  response.send(JSON.stringify(person))
});
app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/5_ajax_解析json数据.html");
 })

5. ajax_ parse json data. html

btn.onclick = function(){
    // 1 
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
	    console.log(xhr.response);//返回的数据
	 }
	/* 手动解析json
	const {name,age,sex}= JSON.parse(xhr.response);//返回的数据 解构赋值
	 */
	const {name,age,sex} = xhr.response;
	content.innerHTML=(`
	<ul>
		<li>姓名:${name}</li>
		<li>年龄:${age}</li>
		<li>性别:${sex}</li>
	</ul>`)
     }
    
   // 2 指定发送请求的:method、url、参数
   xhr.open('GET','http://127.0.0.1:8080/get_person') 

   // responseType用于指定返回数据的格式
   xhr.responseType='json'

   // 3 发送请求
   xhr.send();
 
 }

2.5 Continuous writing method of destructuring assignment (supplement)

let obj= {a:1,b:{c:2}}
//标准解构赋值
const {c} = obj.b
//连续解构赋值
const {b:{c}}=obj
console.log(c);
//连续解构赋值+重命名
const {b:{c:value}}=obj
console.log(alue);

2.6 IE cache problem (time stamp)

Status code 304 means the server has requested

server.js

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

app.use(express.static(__dirname+'/src'))
// 响应GET请求
app.get('/get_person',(request,response)=>{
  console.log("有人请求get_person了");
  const person ={name:'海峰',age:18,sex='女'}
  response.send(JSON.stringify(person))
});
app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/6_ajax_处理IE浏览器GET请求缓存问题.html");
 })

6. ajax_ handles IE browser GET request caching problem. html

IE cache problem: The link requested is the same each time, IE finds that the link is the same as the previous one, does not connect to the server, and returns the previous data.

btn.onclick = function(){
    // 1 
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
	    console.log(xhr.response);//返回的数据
	     }
    }
   // 2 指定发送请求的:method、url、参数
   // 加个时间戳,使每次请求的链接不同
   xhr.open('GET','http://127.0.0.1:8080/get_person?time='+Date.now()) 

   // responseType用于指定返回数据的格式
   xhr.responseType='json'

   // 3 发送请求
   xhr.send();
 }

2.7 Exception and timeout handling of ajax requests

 xhr.onerror ( ) handle request exception

xhr.ontimeout ( ) processing request timeout

server.js

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

app.use(express.static(__dirname+'/src'))
// 响应GET请求
app.get('/get_person',(request,response)=>{
  console.log("有人请求get_person了");
  const person ={name:'海峰',age:18,sex='女'}
  response.send(JSON.stringify(person))
});

// 延迟---响应GET请求
app.get('/get_person_delay',(request,response)=>{
  console.log("有人请求get_person了");
  const person ={name:'tom',age:18,sex='女'}
  setTimeout(()=>{
        //设置响应体
   		response.send(JSON.stringify(person));
  },3000)
 
});
app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/7_ajax_请求的异常与超时处理.html");
 })

7. Abnormal and timeout processing of ajax_ request. html

btn.onclick = function(){
    // 1 
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
	    console.log(xhr.response);//返回的数据
	     }
    }
    // 2 指定发送请求的:method、url、参数
    // xhr.open('GET','http://127.0.0.1:8080/get_person') 
	xhr.open('GET','http://127.0.0.1:8080/get_person_delay') //带延迟的
   
    // responseType用于指定返回数据的格式
    xhr.responseType='json'

    // 出错的回调
    xhr.onerror = function(){
        alert('你的网络似乎出了一点问题');
    }
    // 超时时间
    xhr.timeout = 2000;
    // 超时的回调(如果超时了调用)
    xhr.ontimeout = function(){
        alert('网速不给力,超时了');
    }
    // 3 发送请求
    xhr.send();
 }

2.8 ajax cancel request xhr.abort( )

8. ajax_cancel request.html

For cancellation requests, some of the requests were received by the server and did not return after cancellation; some of them were canceled before the server sent them.

let xhr;  //定义在外面 
const btn1 = document.getElementsByTagName('button')[0];
//取消的按钮
const btn2 = document.getElementsByTagName('button')[1];
btn1.onclick = function(){
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
	        console.log(xhr.response);//返回的数据
	    }
    }
    // 2 指定发送请求的:method、url、参数
	xhr.open('GET','http://127.0.0.1:8080/get_person_delay') //带延迟的
    // responseType用于指定返回数据的格式
    xhr.responseType='json'
    // 出错的回调
    xhr.onerror = function(){
        alert('你的网络似乎出了一点问题');
    }
    // 超时时间
    xhr.timeout = 2000;
    // 超时的回调
    xhr.ontimeout = function(){
        alert('网速不给力,超时了');
    }
    // 3 发送请求
    xhr.send();
 }

btn2.onclick = function(){
	// 取消请求,如果数据已经回来了就取消不了了,如果来得及就会取消
	xhr.abort();
}

2.9 Avoid multiple repeated requests

9. ajax_ avoid multiple repeated requests. html

let xhr;  //定义在外面 
let isLoading;// 是否正在发送AJAX请求
const btn1 = document.getElementsByTagName('button')[0];
btn1.onclick = function(){
	// 设置标志位:如果已经发送请求,之前的就被干掉
	if(isLoading)  xhr.abort(); 
	
    // 1 实例xhr
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300){	
            // 数据已经返回,将标志设为false	
	    	isLoading = false;
	    	console.log(xhr.response);//返回的数据
	     }
    }

    // 2 配置请求
    xhr.open('GET','http://127.0.0.1:8080/get_person_delay') //带延迟的
    xhr.responseType = 'json'
    
    // 3 发送请求
    xhr.send();
    isLoading = true;
 }

btn2.onclick = function(){
	// 取消请求,如果数据已经回来了就取消不了了,如果来得及就会取消
	xhr.abort();
}

3. jQuery encapsulates Ajax

server.js

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

app.use(express.static(__dirname+'/src'))

// 响应GET请求
app.get('/test_jquery_get',(request,response)=>{
  console.log("有人请求test_jquery_get了",request.query);
  const car = {name:'马自达', price:'25万'}
  response.send(JSON.stringify(car))
});

// 响应POST请求
app.post('/test_jquery_post',(request,response)=>{
  console.log("有人请求test_jquery_get了",request.body);
  const car = {name:'马自达', price:'25万'}
  response.send(JSON.stringify(car))
});

app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/10_JQuery封装的ajax.html");
 })

10. ajax.html encapsulated by JQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>10_JQuery封装的ajax/title>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
	<h2 >jQuery封装的ajax</h2>
	<button id="btn1">点我发送请求(JQuery-ajax-get)</button>
	<button id="btn2">点我发送请求(JQuery-ajax-post)</button>
	<button class="btn btn-info">通用型方法ajax</button>
	<script type="text/javascript" >
	const btn1=$('#btn1')
	const btn2=$('#btn2')
	const content=$('#content')
	
     // 1.使用jquery发送get请求(完整版)
     btn1.click(()=>{
     	$.ajax({
			url:'http://127.0.0.1/test_jquery_get',
			method:'GET',//请求类型,默认get
			dataType: 'JSON',//配置相应数据格式
			data:{school:'atguigu'},//携带的数据
            timeout: 2000,//超时时间
            // 成功的回调
			success:(result,responeText,xhr)=>{
			    // responeText:success,error                
                console.log(result,responeText,xhr);
				content.append(`<div>汽车名:${result.name},价格${result.price}</div>`)
			},
            // 失败的回调
			error:(xhr)=>{ console.log('请求出错了',xhr);}
		})
     })

  	 // 2.使用jquery发送get请求(精简版)
     btn1.click(()=>{
     	$.get('http://127.0.0.1/test_jquery_get',{school:'atguigu'},(data)=>{
     		console.log(data);
     	},'json')
     })

  	 // 3.使用jquery发送post请求(完整版)
     btn1.click(()=>{
     	$.ajax({
			url:'http://127.0.0.1/test_jquery_post',
			method:'POST',//请求类型,默认get
			dataType: 'JSON',//配置相应数据格式
			data:{school:'atguigu'},//携带的数据
            timeout: 2000,//超时时间
            // 成功的回调
			success:(result,responeText,xhr)=>{
                //responeText:success,error
				console.log(result,responeText,xhr);
				content.append(`<div>汽车名:${result.name},价格${result.price}</div>`)
			},
            // 失败的回调
			error:(xhr)=>{ console.log('请求出错了',xhr);}
		})
     })

     // 4.使用jquery发送post请求(精简版)
     btn1.click(()=>{
     	$.post('http://127.0.0.1/test_jquery_post',{school:'atguigu'},(data)=>{
     		console.log(data);
     	},'json')
     })

    </script>
</body>
</html>

4. Cross domain

1. Same origin:
If the protocols, domain names, and port numbers of two pages (interfaces) are the same, we consider them to have the same origin

2. Same-origin policy: The same-origin policy is a security restriction
of the browser , which prevents data interaction between different [domains]

3. Harm without same-origin policy:
If there is no same-origin policy, resources can be operated between any sites. When you visit a legitimate website, you open a malicious website, which contains malicious scripts. All resources on legal websites can be operated.

4. Restriction of non-same-origin policy:
1. Cookies from different sources cannot be obtained.
If LocalStorage and indexDB can obtain user’s cookie information from different sources, wouldn’t it be terrible to be manipulated by malicious people, so this is to prevent malicious Restrictions on how a website can obtain cookie data from other websites for users.
2. Don’t allow access to non-same-source DOM.
Take a chestnut: If there is no such item, a malicious website can open the bank page through an iframe, and obtaining the dom is equivalent to obtaining the information of the entire bank page.
3. It is not possible to send non-same-origin ajax requests
(accurately speaking, it should be possible to initiate requests to non-same-origin servers, but the returned data will be intercepted by the browser)

4.1 JSONP solves cross-domain (not required for work, frequently asked in interviews) (handwritten)

1. What is JSONP

The jsonp cross-domain is actually a proxy mode in the JavaScript design mode. It is allowed by the browser to load static resource files from different domain names through corresponding tags in the html page , so we can use this "criminal loophole" to perform cross-domain. Generally, we can dynamically create script tags, and then request a URL with parameters to achieve cross-domain communication.
JSONP is an unofficial cross-domain solution, developed purely with the ingenuity of programmers, and the defect is that it only supports get requests.

Bypass xhr and send requests with script tags

There is a feeling that the front end defines the function and the back end calls the function.

Summary: Use the feature that the src attribute of the script tag is not restricted by the same-origin policy.

server.js

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

app.use(express.static(__dirname+'/src'))
// 响应GET请求
app.get('/test_jsonp',(request,response)=>{
  //json.stringify()将JavaScript对象或值转换为JSON字符串
  const person =[{name:'老刘',age:18},{name:'tom',age:20}]
  //response.send(`demo(${JSON.stringify(person)})`)
  const {callback} = request.query
  response.send(`${callback}(${JSON.stringify(person)})`)
});
});
app.listen(8000, () => {
  console.log("服务已经启动,测试地址如下:");
  console.log("http://127.0.0.1:8080/13_JSONP解决跨域.html");
 })

13. JSONP solves cross-domain.html

btn.onclick = function(){	
	// 1. 创建script节点
	const scriptNode = document.createElement("script");
	// 2. 给节点指定src属性(请求地址)
	// 把函数名也传过去
	scriptNode.src = 'http://localhost:8080/test_jsonp?callback=peiqi'
	// 3. 将节点放入页面
	document.body.appendChild(scriptNode)
    const xhr = new XMLHttpRequest();
    // window.demo=(a)=>{
    // 4. 准备一个函数
    // 动态的函数名
    window.peqi=(a)=>{ 
		console.log(a)
	}
	// 5. 移除已经使用过得script节点
	document.body.removeChild(scriptNode)
 }

The difference between JSON and JSONP!
But so far the most recommended or preferred solution is to use JSON to transfer data and rely on JSONP to cross domains.
Although there is only one letter difference between JSON and JSONP, they are not the same thing at all: JSON is a data exchange format, while JSONP is an unofficial cross-domain data exchange protocol.
The full name of jsonp is json with padding , which is very vivid. It is to wrap the json object in a form that conforms to the js syntax so that other websites can request it, that is, to encapsulate the json data into a js file; json is an ideal data exchange format,
but There is no way to get it directly across domains, so the json package (padding) is passed in a legal js statement as a js file. This is the difference between json and jsonp. json is what you want, and jsonp is a method commonly used to achieve this goal. Of course, json is finally obtained and processed. So json is the purpose, jsonp is just the means. json is always used, and jsonp is only used when obtaining data across domains

Disadvantages of JSONP
1. It only supports GET requests but not other types of HTTP requests such as POST.
2. It only supports cross-domain HTTP requests, and cannot solve the problem of how to make JavaScript calls between two pages of different domains.
3 jsonp will not return various HTTP status codes when the call fails.
4 The disadvantage is security . If there is a page injection vulnerability in the service that provides jsonp, that is, the content of the javascript it returns is controlled by someone. So what was the result? All websites that call this jsonp will have vulnerabilities. So it is impossible to control the danger under one domain name... So when using jsonp, you must ensure that the jsonp service you use must be safe and reliable.

4.2 JQuery encapsulates JSONP

const btn= $("#btn")
$("#btn").click(()=>{
	$.getJSON("http://localhost:8080/test_jsonp?callback=?", {},(data)=>{
		 console.log(data);
     });
 });

4.3 CORS solves cross domain (backend technology)

Set the response header Access-Control-Allow-Origin

server.js

app.get('/test_get', (request, response) => {
  console.log("有人请求test_get了,携带的query参数是:",request.query);
  // 设置响应头
  // Access-Control-Allow-Origin
  response.setHeader("Access-Control-Allow-Origin", "*")//任何网站都可以拿数据
  //response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500")
  response.setHeader("Access-Control-Allow-Headers", '*');
  response.setHeader("Access-Control-Allow-Method", '*');
  response.send("Hello_test_get");
});
app.options('/test_put', (request, response) => {
  response.setHeader("Access-Control-Allow-Origin", "*")
  response.setHeader("Access-Control-Allow-Headers", '*');
  response.setHeader("Access-Control-Allow-Method", '*');
  response.send("Hello_test_get");
});
app.put('/test_put', (request, response) => {
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Headers", '*');
  response.setHeader("Access-Control-Allow-Method", '*');
  response.send("Hello");
});

btn.onclick = function(){
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
	    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
	    console.log(xhr.response);//返回的数据
	     }
    }

	xhr.open('GET','http://localhost:8080/test_get')
	//xhr.open('PUT','http://localhost:8080/test_get')
	xhr.send()
 }

Install cors
yarn add cors

server.js

// cors中间件
const cors = require('cors')
app.use(cors())
app.get('/test_get', (request, response) => {
  console.log("有人请求test_get了,携带的query参数是:",request.query);
  response.send("Hello_test_get");
});

cors solves cross-domain

  1. The front end does not need any operation, it is done by the back end
  2. Not two response headers can be achieved, a set of response headers is required
  3. put and delete are not simple requests, they are complex requests, and a pre-request (sniffing request) is required before the real request

Advantages and disadvantages of CORS:

Advantages of CORS: You can send any request.
Disadvantages of CORS:
When it comes to complex requests, you have to do a pre-check before sending the real request. There will be a performance loss if two requests are made

5 get and post

GET

  1. Meaning: Get data from the specified resource
  2. When is it appropriate to use a GET request?
    (1) When simply obtaining data
    (2) When requesting non-sensitive data
  3. Common GET requests:

1 When entering the URL in the address bar of the browser, (that is, when the browser requests the page, and cannot be changed manually)
2 HTML tags of external resources can be requested, for example: <img><a><link><script>and cannot be changed manually
3 If the method of sending the request is not specified when sending ajax, then Use the function GET, or clearly point out the use of GET to request
4 form form submission, if there is no specified method, then use get

POST

  1. Meaning: want the specified resource to submit the data to be processed
  2. When is it appropriate to use a POST request?
    (1) When transmitting relatively sensitive data
    (2) The result of the request has persistent side effects, for example: when the transmitted data is to be written to the database
    Note: Using POST does not mean absolute security
  3. Common POST requests:

1 When sending ajax, it is clearly pointed out that the post method is used
2 When using a third-party request library, it is clearly pointed out that the post method is used
3 When the form is submitted, it is clearly pointed out that the post method

get means that there will be a bunch of key=value&key=value in the browser address bar...

The difference between a get request and a post request:
   ①  post is safer than get (because the post parameters are in the request body and the get parameters are on the url)

   ② The transmission speed of get is faster than that of post,  which is determined according to the parameters. (Post passes parameters through the request body, and the background receives them through data streams. The speed is slightly slower. Get can be directly obtained by passing parameters through url)

   ③  There is no limit to the large theory of post transfer files  , get transfer files are about 2-8k, more common is less than 1k

  ④ The get request refreshes the server or rollback has no effect, and the data request will be resubmitted when the post request rolls back.

  ⑤ get requests can be cached, post requests will not be cached

  ⑥ Get requests can only be url-encoded (application-x-www-form-urlencoded), and post requests support multiple types (multipart/form-data, etc.).

Guess you like

Origin blog.csdn.net/qq_37308779/article/details/126248480