当前位置:网站首页>JS all network request modes
JS all network request modes
2022-06-27 10:16:00 【Xiaaoke】
List of articles
HTTP
HTTP(hypertext transport protocol) agreement 『 Hypertext transfer protocol 』, The protocol specifies the rules of communication between browser and World Wide Web server .
Request message
The focus is on format and parameters
That's ok POST /s?ie=utf-8 HTTP/1.1
head Host: atguigu.com
Cookie: name=guigu
Content-type: application/x-www-form-urlencoded
User-Agent: chrome 83
Blank line
body username=admin&password=admin
response message
That's ok HTTP/1.1 200 OK
head Content-Type: text/html;charset=utf-8
Content-length: 2048
Content-encoding: gzip
Blank line
body <html>
<head>
</head>
<body>
<h1> Silicon Valley </h1>
</body>
</html>
Common status codes
- 1XX: Specify some actions corresponding to the client
- 2XX: success
- 3XX: A file that has been moved and is contained in the location header information ( Redirect , In order to complete the request , Required actions )
- 4XX: Client error
- 5XX: Server error
- 404: No files found
- 403: The server has been requested , But refuse to execute
- 401: Current request requires user authentication
- 400: Invalid request
- 500: Server internal problems
- 200: The request is successful
- 304: not changed , The requested resource has not been modified
readyState attribute
- 0: uninitialized (Uninitialized). Not yet invoked open() Method .
- 1: Already opened (Open). Already called open() Method , Not yet invoked send() Method .
- 2: Has been sent (Sent). Already called send() Method , No response has been received .
- 3: Receiving (Receiving). Partial response has been received .
- 4: complete (Complete). All responses have been received , It's ready to use
Native AJAX
AJAX brief introduction
- AJAX Its full name is Asynchronous JavaScript And XML, It's asynchronous JS and XML.
- asynchronous : Will not occupy js The main thread , Instead, call the child threads of the thread pool ( Network request thread )
- The implementation syntax is mainly JavaScript
- xml: Belong to html Brother . Because it is too troublesome to parse , All are now gradually being json Instead of
- adopt AJAX You can send asynchronous requests to the server in the browser , The biggest advantage : No refresh to get data .
- AJAX It's not a new programming language , It is a new way to combine existing standards .
XML brief introduction
- XML Extensible markup language .
- XML Designed to transmit and store data .
- XML and HTML similar , The difference is HTML Are predefined labels in , and XML There are no predefined labels in ,
- It's all custom labels , Used to represent some data .
For example, I have a student data :name = " The Monkey King " ; age = 18 ; gender = " male " ;
// use XML Express :
<student>
<name> The Monkey King </name>
<age>18</age>
<gender> male </gender>
</student>
// use JSON Express :
{
"name":" The Monkey King ","age":18,"gender":" male "}
Now it's basically JSON To replace the .
AJAX Characteristics
AJAX The advantages of
- You can communicate with the server without refreshing the page .
- Allows you to update some page content according to user events .
AJAX The shortcomings of
- No browsing history , Can't back
- There are cross-domain problems ( Homology )
- SEO unfriendly
AJAX Use
The core object :XMLHttpRequest,AJAX All operations of are performed through this object
// 1) establish XMLHttpRequest object
let xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// Set the type of response body data
xhr.responseType = 'json';
// timeout 2s Set up
xhr.timeout = 2000;
// Timeout callback
xhr.ontimeout = function(){
alert(" Network anomalies , Please try again later !!");
}
// Network exception callback
xhr.onerror = function(){
alert(" There seems to be something wrong with your network !");
}
// 2) Set request information
xhr.open(method, url);
// You can set the request header , Generally not set
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// 3) Send a request
xhr.send(body) //get Request not to transmit body Parameters , Only post Request to use
// 4) Receiving response
//xhr.responseXML receive xml Response data in format
//xhr.responseText The format of the response data
//JSON.parse(xhr.response) take json The file is converted to js data
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
console.log(xhr.responseText); // The text returned as a response body
} else {
console.log("Request was unsuccessful: " + xhr.status); // request was aborted , return Responsive HTTP state
}
}
};
// Cancel the request :xhr.abort();
// get Request parameter splicing method
const addURLParam = (url, name, value) => {
url += (url.indexOf("?") == -1 ? "?" : "&");
url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
return url;
}
// post Form transfer parameters
let form = document.getElementById("user-info");
xhr.send(new FormData(form));
Usually write 1~4 Step by step
solve IE The cache problem
problem : In some browsers (IE), Because of the cache mechanism ,ajax Only the first request will be sent , Remnant
The remaining requests are not sent to the browser, but directly load the data in the cache .
Solution : The browser cache is based on url Address to record , So we just need to modify url Address
To avoid cache problems
xhr.open("get","/testAJAX?t="+Date.now());
ajax The state of return
- 0:( uninitialized ) Not called yet send() Method
- 1:( load ) Already called send() Method , Sending request
- 2:( Loading completed )send() Method execution complete , All response contents have been accepted
- 3:( Interaction ) Parsing response content
- 4:( complete ) Response content parsing completed , Can be called on the client
jQuery-AJAX
get request
$.get(url, [data], [callback], [type])
- url: Requested URL Address .
- data: The parameter that the request carries .
- callback: Callback function on load success .
- type: Format the returned content ,xml, html, script, json, text, _default
post request
$.post(url, [data], [callback], [type])
- url: Requested URL Address .
- data: The parameter that the request carries .
- callback: Callback function on load success .
- type: Format the returned content ,xml, html, script, json, text, _default
ajax request
$.ajax({
//url
url: 'http://127.0.0.1:8000/jquery-server',
// Parameters
data: {
a:100, b:200},
// Request type
type: 'GET',
// Response body results
dataType: 'json',
// Successful callback
success: function(data){
console.log(data);
},
// Timeout time
timeout: 2000,
// Failed callback
error: function(){
console.log(' Error !!');
},
// Header information
headers: {
c:300,
d:400
}
});
Axios-AJAX
More detailed reference React Use in axios
get request
// The default configuration
axios.defaults.method = 'GET';// Set the default request type to GET
axios.defaults.baseURL = 'http://localhost:3000';// Set the foundation URL
axios.defaults.params = {
id:100};
axios.defaults.timeout = 3000;//
// To configure baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8000';
axios.get('/axios-server', {
//url Parameters
params: {
id: 100,
vip: 7
},
// Request header information
headers: {
name: 'atguigu',
age: 20
}
}).then(value => {
console.log(value);
});
// Cancel the request :cancel();
post request
// To configure baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8000';
axios.post('/axios-server', {
username: 'admin',
password: 'admin'
}, {
//url
params: {
id: 200,
vip: 9
},
// Request header parameters
headers: {
height: 180,
weight: 180,
}
});
ajax request
// The traditional way
axios({
methods: ' Request mode ',
url: ' Request address ',
params: {
// get
Parameter name : Parameter values
},
data: {
// post put patch
Parameter name : Parameter values
}
})
.then(res => {
// Processing after successful request
// res Is the response data returned by the server
})
.catch(err => {
// Processing after a request fails
// err Is the information after the request fails
})
// get request
axios.get("url", {
params: {
Parameter name : Parameter values }})
.then(res => {
})
.catch(err => {
})
// post request : Send form data and file upload
axios.post("url", {
Parameter name : Parameter values })
.then(res => {
}).catch(err => {
})
// put request : Update all data
axios.put("url", {
Parameter name : Parameter values })
.then(res => {
}).catch(err => {
})
// patch request : Update only changed data
axios.patch("url", {
Parameter name : Parameter values })
.then(res => {
}).catch(err => {
})
// delete request : Delete request ( Parameters can be placed in url On , Can also be combined with post Put it in the request body )
axios.delete('url', {
params: {
Parameter name : Parameter values
}
}).then(res => {
}).catch(err => {
})
axios.delete('url', {
data: {
Parameter name : Parameter values }})
.then(res => {
})
.catch(err => {
})
Fetch-AJAX
fetch('http://127.0.0.1:8000/fetch-server?vip=10', {
// Request method
method: 'POST',
// Request header
headers: {
name:'atguigu'
},
// Request body
body: 'username=admin&password=admin'
}).then(response => {
// return response.text();
return response.json();
}).then(response=>{
console.log(response);
});
Cross domain
The same-origin policy
The same-origin policy (Same-Origin Policy) The earliest by Netscape The company proposed , Is a security policy for browsers .
Homology : agreement 、 domain name 、 Port number It must be exactly the same .
Violating the homology strategy is cross domain .
How to solve cross domain
JSONP
JSONP What is it?
JSONP(JSON with Padding), Is an unofficial cross domain solution , Rely solely on the ingenuity of programmers
Intelligence developed , Only support get request
JSONP How does it work ?
Some tags on Web pages are inherently cross domain , such as :img link iframe script. JSONP Is the use script Tag's cross domain capability to send requests
JSONP Use
// 1. Create a dynamic script label
var script = document.createElement("script");
// 2. Set up script Of src, Set the callback function
script.src = "http://localhost:3000/testAJAX?callback=abc";
function abc(data) {
alert(data.name);
};
// 3. take script Add to body in
document.body.appendChild(script);
// 4. Processing of routing in the server
router.get("/testAJAX" , function (req , res) {
console.log(" Receive a request ");
var callback = req.query.callback;
var obj = {
name:" The Monkey King ",
age:18
}
res.send(callback+"("+JSON.stringify(obj)+")");
});
jQuery-jsonp
$.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?', function(data){
$('#result').html(` name : ${
data.name}<br> Campus : ${
data.city} `)
});
CORS
CORS What is it? ?
CORS(Cross-Origin Resource Sharing), Cross-domain resource sharing .CORS Is the official cross domain solution , Its characteristic is that it does not need to do any special operation on the client , Completely processed in the server , Support get and post request . A new set of standards for cross domain resource sharing has been added HTTP Header field , Allow the server to declare which origin has access to which resources through the browser
CORS How does it work ?
CORS It tells the browser by setting a response header , The request allows cross domain , The browser received the response
The response will be released later .
CORS Use
// Mainly server-side settings :
router.get("/testAJAX" , function (req , res) {
// adopt res To set the response header , To allow cross domain requests
//res.set("Access-Control-Allow-Origin","http://127.0.0.1:3000");
res.set("Access-Control-Allow-Origin","*");
res.send("testAJAX Response returned ");
});
What is used node Service code
//1. introduce express
const express = require('express');
//2. Create application objects
const app = express();
//3. Create routing rules
// request It is the encapsulation of request message
// response It is the encapsulation of response message
app.get('/server', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
// Set the response body
response.send('HELLO AJAX - 2');
});
// Can receive any type of request
app.all('/server', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
// Response head
response.setHeader('Access-Control-Allow-Headers', '*');
// Set the response body
response.send('HELLO AJAX POST');
});
//JSON Respond to
app.all('/json-server', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
// Response head
response.setHeader('Access-Control-Allow-Headers', '*');
// Respond to a data
const data = {
name: 'atguigu'
};
// String conversion of objects
let str = JSON.stringify(data);
// Set the response body
response.send(str);
});
// in the light of IE cache
app.get('/ie', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
// Set the response body
response.send('HELLO IE - 5');
});
// Delayed response
app.all('/delay', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
setTimeout(() => {
// Set the response body
response.send(' Delayed response ');
}, 1000)
});
//jQuery service
app.all('/jquery-server', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
// response.send('Hello jQuery AJAX');
const data = {
name:' Silicon Valley '};
response.send(JSON.stringify(data));
});
//axios service
app.all('/axios-server', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
// response.send('Hello jQuery AJAX');
const data = {
name:' Silicon Valley '};
response.send(JSON.stringify(data));
});
//fetch service
app.all('/fetch-server', (request, response) => {
// Set the response header Set allow cross domain
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*');
// response.send('Hello jQuery AJAX');
const data = {
name:' Silicon Valley '};
response.send(JSON.stringify(data));
});
//jsonp service
app.all('/jsonp-server',(request, response) => {
// response.send('console.log("hello jsonp")');
const data = {
name: ' Silicon Valley atguigu'
};
// Convert data to a string
let str = JSON.stringify(data);
// Return results
response.end(`handle(${
str})`);
});
// User name detection exists
app.all('/check-username',(request, response) => {
// response.send('console.log("hello jsonp")');
const data = {
exist: 1,
msg: ' The user name already exists '
};
// Convert data to a string
let str = JSON.stringify(data);
// Return results
response.end(`handle(${
str})`);
});
//
app.all('/jquery-jsonp-server',(request, response) => {
// response.send('console.log("hello jsonp")');
const data = {
name:' Silicon Valley ',
city: [' Beijing ',' Shanghai ',' Shenzhen ']
};
// Convert data to a string
let str = JSON.stringify(data);
// receive callback Parameters
let cb = request.query.callback;
// Return results
response.end(`${
cb}(${
str})`);
});
app.all('/cors-server', (request, response)=>{
// Set the response header
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", '*');
response.setHeader("Access-Control-Allow-Method", '*');
// response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
response.send('hello CORS');
});
//4. Listening port starts service
app.listen(8000, () => {
console.log(" Service started , 8000 Port monitoring ....");
});
Web Socket
Web Socket( Socket ) The goal is to achieve full duplex with the server through a long-term connection 、 Two way communication . stay JavaScript
Created in Web Socket when , One HTTP The request is sent to the server to initialize the connection . After the server responds , Connection to use HTTP
Of Upgrade Head from HTTP The protocol switches to Web Socket agreement . It means Web Socket Can't pass the standard HTTP service
Implementation of the processor , Instead, you must use a proprietary server that supports the protocol .
because Web Socket Using custom protocol , therefore URL programme (scheme) There was a slight change : No more use http:// or https://,
And you want to use ws:// and wss://. The former is an insecure connection , The latter is secure connection . In the specified Web Socket URL when , Must pack
contain URL programme , Because it is possible to support other schemes in the future .
Use custom protocols instead of HTTP The benefits of the agreement are , Very little data can be sent between the client and the server , It won't be right
HTTP Cause any burden . Use smaller packets to make Web Socket It is very suitable for mobile applications with obvious bandwidth and delay problems .
The disadvantages of using custom protocols are , Defining an agreement takes longer than defining JavaScript API longer .Web Socket I got all the mainstream
Browser support
// establish WebSocket
let socket = new WebSocket("ws://www.example.com/server.php");
// readyState Property indicates the current state .
// - WebSocket.OPENING(0): Connection is being established .
// - WebSocket.OPEN(1): Connection established .
// - WebSocket.CLOSING(2): The connection is closing .
// - WebSocket.CLOSE(3): Connection closed .
// send data
let stringData = "Hello world!"; // character string
let arrayBufferData = Uint8Array.from(['f', 'o', 'o']); // ArrayBuffe
let blobData = new Blob(['f', 'o', 'o']); // Blob
socket.send(stringData);
socket.send(arrayBufferData.buffer);
socket.send(blobData);
// Receive data
socket.onmessage = function(event) {
let data = event.data;
// Perform some operations on the data
};
// Triggered when the connection is successfully established
socket.onopen = function() {
alert("Connection established.");
};
// Trigger... When an error occurs . The connection cannot survive
socket.onerror = function() {
alert("Connection error.");
};
// Trigger... When the connection is closed
socket.onclose = function() {
alert("Connection closed.");
};
边栏推荐
- Comparison between new and old interfaces
- 【OpenCV 例程200篇】211. 绘制垂直矩形
- 三层架构中,数据库的设计在哪一层实现,不是在数据存储层吗?
- 通俗易懂理解朴素贝叶斯分类的拉普拉斯平滑
- 浅析基于边缘计算的移动AR实现(中)
- [STM32] Hal library stm32cubemx tutorial 12 - IIC (read AT24C02)
- Explain the imaging principle of various optical instruments in detail
- Learning notes - data set generation
- 前馈-反馈控制系统设计(过程控制课程设计matlab/simulink)
- Ubuntu manually installing MySQL
猜你喜欢

Win10 shortcut key sorting

Tdengine invitation: be a superhero who uses technology to change the world and become TD hero

基于STM32设计的蓝牙健康管理设备

三层架构中,数据库的设计在哪一层实现,不是在数据存储层吗?

Easy to understand Laplace smoothing of naive Bayesian classification

小哥凭“量子速读”绝技吸粉59万:看街景图0.1秒,“啪的一下”在世界地图精准找到!...

On anchors in object detection

es 根据索引名称和索引字段更新值

leetcode:968. 监控二叉树【树状dp,维护每个节点子树的三个状态,非常难想权当学习,类比打家劫舍3】

以后发现漏洞,禁止告诉中国!
随机推荐
2021 CSP J2入门组 CSP-S2提高组 第2轮 视频与题解
torch. utils. data. Randomsampler and torch utils. data. Differences between sequentialsampler
【HCIE-RS复习思维导图】- STP
R language plot visualization: visualize the normalized histograms of multiple data sets, add density curve KDE to the histograms, set different histograms to use different bin sizes, and add edge whi
[noodle classic] Yunze Technology
Product strength benchmarking seal /model 3, with 179800 pre-sales of Chang'an dark blue sl03
[200 opencv routines] 212 Draw a slanted rectangle
有关WIN10的内存压缩
.NET 中的引用程序集
Curiosity mechanism in reinforcement learning
新旧两个界面对比
Exception in Chinese character fuzzy query of MySQL database
[cloud enjoys freshness] community weekly · vol.68- Huawei cloud recruits partners in the field of industrial intelligence to provide strong support + business realization
C# Any()和AII()方法
【STM32】HAL库 STM32CubeMX教程十二—IIC(读取AT24C02 )
详细记录YOLACT实例分割ncnn实现
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
Google browser chropath plug-in
Easy to understand Laplace smoothing of naive Bayesian classification
Quartz(定时器)