当前位置:网站首页>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.");
};
边栏推荐
- torchvision.models._utils.IntermediateLayerGetter使用教程
- DNS standby server information, DNS server address (how many DNS preferred and standby are filled in)
- 迪米特法则
- 通俗易懂理解樸素貝葉斯分類的拉普拉斯平滑
- mongodb跨主机数据库拷贝以及常用命令
- Memory compression for win10
- R langage plotly visualisation: visualisation de plusieurs histogrammes normalisés d'ensembles de données et ajout d'une courbe de densité KDE à l'histogramme, réglage de différents histogrammes en ut
- Reorganize common shell scripts for operation and maintenance frontline work
- Explain the imaging principle of various optical instruments in detail
- The tutor invites you to continue your doctoral study with him. Will you agree immediately?
猜你喜欢

This application failed to start because it could not find or load the QT platform plugin

Decompile the jar package and recompile it into a jar package after modification

Win10快捷键整理

If you find any loopholes later, don't tell China!

产品力对标海豹/Model 3,长安深蓝SL03预售17.98万起
![[200 opencv routines] 211 Draw vertical rectangle](/img/57/5ff4ccb6f003e1ec6c49de8c8fde16.png)
[200 opencv routines] 211 Draw vertical rectangle

C# Any()和AII()方法

Learning notes - data set generation

反编译jar包,修改后重新编译为jar包

前馈-反馈控制系统设计(过程控制课程设计matlab/simulink)
随机推荐
[registration] infrastructure design: from architecture hot issues to industry changes | tf63
C语言学习-Day_06
Location and solution of network connection failure of primary online mobile terminal Report
Test how students participate in codereview
10 常见网站安全攻击手段及防御方法
6月23日《Rust唠嗑室》第三期B站视频地址
oracle触发器 存储过程同时写入
mongodb跨主机数据库拷贝以及常用命令
LVI Sam summary
【报名】基础架构设计:从架构热点问题到行业变迁 | TF63
R語言plotly可視化:可視化多個數據集歸一化直方圖(historgram)並在直方圖中添加密度曲線kde、設置不同的直方圖使用不同的分箱大小(bin size)、在直方圖的底部邊緣添加邊緣軸須圖
基于STM32设计的蓝牙健康管理设备
2-4 installation of Nessus under Kali
【OpenCV 例程200篇】212. 绘制倾斜的矩形
你睡觉时大脑真在自动学习!首个人体实验证据来了:加速1-4倍重放,深度睡眠阶段效果最好...
DNS standby server information, DNS server address (how many DNS preferred and standby are filled in)
Use of bufferedwriter and BufferedReader
Easy to understand Laplace smoothing of naive Bayesian classification
Decompile the jar package and recompile it into a jar package after modification
unity--newtonsoft. JSON parsing