Basic concept
Intranet IP address (LAN)
In an area, everyone is connected to the same network (to be precise: connecting to the same wifi is not necessarily the same network, connecting to different wifi may be the same network, depending on the configuration of the routing switch), this is a LAN
Under the same LOCAL area network, members can access each other (your computer is connected to NETWORK A, and your mobile phone is also connected to network A, so your mobile phone can access some information on the computer => In this way, you can do mobile phone joint modulation during mobile terminal development, recommend anywhere)
HBuilder also provides syndication functions (code to add breakpoints, phone access, application will walk breakpoints)
IP networks outside
Any user can access the corresponding server through this IP address
Domain name DNS Resolution
Associate the domain name with the server and enter the external IP address of the server during resolution
The DNS system: As a distributed database on the World Wide Web, domain names and IP addresses are mapped to each other. After domain names are successfully resolved, a message “www.baudu.com(domain name) 192.23.42.01(External IP address of the server)” is recorded in the DNS system to associate the domain name with the server, ensuring future access to the domain name. You can directly find the external IP address and access the server through the external IP address
FTP
A tool that transfers local code to the server, usually based on FTP(FileZilla) uploads
You are not allowed to install anything on the server other than the development environment (keep the server clean)
Web Publishing tools
The tool used to publish projects on the server associates the domain name with the project on the server, specifying which project source code is executed after the current domain name accesses the server
Common web publishing tools are: IIS(c#.. – > Windows), APACHE TOMCAT (PHP/JAVA… – > LINUX), NGINX
The server
Server is a high-performance computer, each server corresponds to an external IP address, and each server has its own user name and password
The server side
All can receive the client request, and give its response some content is the server, the server is actually a high performance computer
The client
All sides that can send requests to the server are clients
Question:
What happens when you open a browser, type a url into the address bar, and press Enter to see the entire page?
HTTP request phase: Sends a request to the server
- 1. The browser first sends a request to the DNS server
- 2. DNS reverse resolution: Find the external IP address of the DNS server based on the domain name specified in the address requested by the browser
- 3, through the external IP found, to the corresponding server to send requests (the first access is the server’s WEB site management tool: precisely speaking, we first create a lot of services on the server based on the tool, when there is a client to visit, the server will match the specific request which service)
- 4. Find the corresponding service on the server and the project source file managed by the service through the port number carried in the URL address
HTTP response phase: The server prepares the content required by the client and returns it to the client
- 5. The server prepares and processes the content required by the client according to the path name, question mark transmission parameter or hash value in the request address
- 6. Respond to the prepared content to the client (if the request is HTML or CSS resource file, the server will return the source code in the resource file, not the file itself (except audio, video and images, which use file stream transfer))
Browser render phase
- 7, the client browser received the source code returned by the server, based on its own internal rendering engine (kernel) began to draw and render the page
- Firstly, DOM structure is calculated and DOM TREE is generated
- Run code from top to bottom, load CSS and other resource content
- Generate a RENDER TREE with styles based on the acquired CSS
- Start rendering and painting
We call a complete request + response “HTTP transaction “, a transaction is a complete operation, request and response are indispensable
When a page is fully loaded, you need to initiate many HTTP transactions to the server. Generally speaking, the HTML source code is taken back and parsed, and the HTML is loaded using the link, script, SRC, iframe, video, img file. Audio [no preload=”none”]…. Both re-establish HTTP transaction interactions with the server
Special case: If we do resource caching (304) and the resource to be loaded has already been loaded before, these operations are different from traditional HTTP transactions, which read data from the server and browser cache much faster than traditional reads
When the client sends a request to the server and the server responds to the client, a lot of content is passed to each other (the client sends some content to the server, and the server sends some content to the client), which is collectively called “HTTP message “.
Front-end performance optimization
1, reduce the number of HTTP requests and the size of the request content, such as all CSS in one file, all scripts in one file, lazy loading of images
The composition of the URL
URI=URL+URI
URI: Uniform resource Identifier (URI)
URL: Uniform resource locator
URN: Specifies the unified resource name
www.zhufengpeixun.cn:80/stu/index.h…
Transfer protocol
Used to transfer information between client and server (similar to Courier)
Transport protocol type
HTTP: Hypertext transfer protocol (in addition to ordinary text, but also can transfer file flow or base code information), is the most commonly used WEB transfer protocol
HTTPS: AN HTTP transport protocol based on Secure Sockets Layer (SSL) encryption, which is more Secure than HTTP. (Websites involving payment are generally implemented over HTTPS.)
FTP: a file transfer protocol used to upload and download resource files on the server
Domain Name (Domain Name)
> level 1 domain name (top-level domain name) qq.com > level 2 domain name sports.qq.com > level 3 domain name kbs.sports.qq.com > QQ.com is a domain name, buy domain name only buy QQ.com, the corresponding level 2 domain name and level 3 domain name is their own '.com ': .cn: Chinese domain name for commercial use. Net: web service providers (system classes often use net domain names). Org: official organizationsCopy the code
The port number
An identifier used to distinguish different services on the same server (which can be specified when the Web services manager creates the service). Different services generally cannot use the same port number
'HTTP' : default port 80. 'HTTPS' : default port 443. 'FTP' : default port 21Copy the code
If the current service of the website uses the default port management corresponding to the protocol, the user can not specify the port number when entering the URL. The browser will pass the default port number to the server by default, but the port number must be written when using the Web publishing tool to publish the service
The port number of a server ranges from 0 to 65535
Webstorm preview page: WS uses its computer as a server, creates a service on the server, port number is 63342, the browser on its computer previews the service on its computer, belongs to the local service request, use localhost(127.0.0.1) local domain name
http://localhost:63342/JS/ / sina App 6 weeks since writing/index. The HTML? _ijt p9s43qdn13nvv9trnnu6u7n = 361
An application installed on the server may take up a port number as a service, so the server generally does not download anything other than what is needed in the development environment
Request path name
path
pathname
For example, /stu/index.html is usually requested in the project directory corresponding to the current service, the index.
There are also special cases where the current URL is “pseudo-URL rewrite” and the URL request we see is not a real request, such as item.jd.com/4679424.htm… This URL is been rewritten, its true URL is likely to be http://item.jd.com/detail.jsp?id=4679424, actually is to jump to the details page, delivering different product code, a question mark show different products details information, But. JSP this kind of server rendering dynamic page can not be included by the search engine, is not conducive to page SEO, so we will put the dynamic page static, which is used to URL rewriting technology
DHTML
JSP /.php/.aspx… The data of these pages are processed based on AJAX or background programming language, rendered by the server, and finally returned to the client for rendering
Such as: /stu/info, which does not have any suffix, is usually not used to request the resource file, but the address of the interface used for AJAX data requests (the same applies if the suffix is.json), except that /stu/info/ is not the address of the interface, but does not specify the requested resource name. The server will request the default resource file, which is usually index.html/default.html
Question mark parameter and hash value
? xxx=xxx&… #xxx
In HTTP transactions, question mark passing is a way for the client to pass information to the server (or perhaps jump to a page and pass parameter values to the page for identification)
Hashes generally have little to do with client server interaction and are used for anchor location and hash route switching in a page
The HTTP message
The starting line
- Request start line: Describes some basic information about the current request
- Start line of response: HTTP status code
Forehead
- Request Headers [set by client, received by server]
GET /? Ref =qipaoxian HTTP/1.1 => start line Host: www.baidu.com Connection: Keep-alive cache-control: max-age=0 upgrade-insecure -Requests: 1 user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, Like Gecko) Version 11.0 / Mobile / 15 a372 Safari/Accept 604.1: text/HTML and application/XHTML + XML, application/XML. Q = 0.9, image/webp image/apng, * / *; Q =0.8 Accept-encoding: gzip, deflate Accept-language: zh-cn,zh; Q = 0.9 cookies:... //=> Cookie information is generally placed in header files to achieve data communication with the serverCopy the code
- Response Headers [set on the server, obtained by the client]
HTTP/1.1 200 OK //=> Start line of response (HTTP status code) Date: Tue, 22 May 2018 09:20:51 GMT //=> Start line of response"Server side time"(When the client obtains the time, there is an error with the real time, because it takes time for the server to return the Content to the client), and the time is GMT (8 hours later than Beijing time, Beijing time is GMT+0800). text/html Transfer-Encoding: chunked Connection: keep-alive Last-Modified: Sun, 06 May 2018 10:02:42 GMT Vary: Accept-encoding, user-agent Server: yunjiasu-nginx //=> Tool for managing WEB services CF-ray: 41EE358b1165b1ee-hkg Content-Encoding: gzipCopy the code
- General Headers
Request URL: http://www.baudu.com/? //=> request address ref=qipaoxian
Request Method: / / = > request: GET/POST/DELETE/PUT/HEAD/OPTION
Status Code: 200 OK //=> HTTP status code of the response
Remote Address: 162.159210.54.:80Host IP address (external IP address of the server) Referrer Policy: no-referreer-when - mustCopy the code
The main body
- Requeset Payload/Form Data
//=> What the client passes to the serverCopy the code
- Response Response body
//=> What the server returns, such as the HTML source codeCopy the code
Work development and BUG debugging
A: Open the console, find the address of the request for the current interaction in Net-work, and click there to see the details
B: If the parameters passed to the server or the way is wrong [front-end problem]
C: If the information returned by the server is incorrect or different from the content specified in the API interface document [background problem]
D: If the returned data is correct, but there is a problem with the presentation [front-end problem]
Once the problem is real in your front end, start debugging step by step, based on breakpoints (or debugger in your code) or console output
How the client and server interact with each other
The client passes to the server
Question marks the participation
At the end of the requested URL, some information is passed to the server /stu/info by question mark. id=12&lx=man
Set the request header
The client sets the content to be sent to the server in the request header (custom request header), which the server can receive to retrieve the content
Set the request body
Xhr.send ([AJAX send, which is the body of the request set by the client, can be received by the server])
The server returns to the client
Set the response header information
For example, if the server time is returned to the client through the response header, the client obtains this time by retrieving the response header information (the speed of the return of the response header takes precedence over the response body) regardless of whether the HTTP request was sent successfully (the value of status), there will be a response header, even if it is 404;
Setting the response body
The main return information is in the response body
AJAX
Async javascript and XML Asynchronous JS and XML
Asynchronism in AJAX is not synchronous asynchronous programming as we understand it, but rather refers to “local refresh”, but we use asynchronous data fetching whenever possible in future AJAX requests (because asynchronous data fetching does not block the execution of the following code)
XML is a file format (we can think of HTML as a kind of XML) : extensible markup language, which is used to store some data and content with its own extended semantic tags. The advantage of such storage is that the structure of the data is clearly displayed
<?xml version="1.0" encoding="utf-8"? >
<root>
<student>
<name>Zhang SAN</name>
<age>25</age>
<score>
<english>98</english>
<chinese>100</chinese>
<math>100</math>
</score>
</student>
<student>
<name>Li si</name>
<age>24</age>
<score>
<english>8</english>
<chinese>90</chinese>
<math>80</math>
</score>
</student>
</root>
Copy the code
In the early days of AJAX, the client would fetch data from the server, and the server would return XML content in order to express the data structure clearly. Now, the data we get is usually JSON content, and JSON can express the data structure clearly compared to XML. And data access inside the easier to operate than XML (but now some projects, the server returned to the client’s data is not just the data, but data and needs to show the structure of the stitching good results (similar to our own do string concatenation), in other words, is the server and the data structure together is returned to us, The data returned is usually a string in XML format.
Front – and back-end project interaction patterns
1. Sending ajax-based requests to the server for data (whether JSON or XML documents rendered by the server) is a separate project from the front and back ends
- Bad for SEO optimization (you can’t see dynamically increased data in the source code)
- You can do local refresh
For example: Jingdong’s first screen data is XML string obtained from the server based on AJAX (server-side rendering), other screen data is JSON obtained from the server, and the client splicing string is inserted into the specified area (client-side rendering).
2,
- A: It’s good for SEO optimization
- B: Only “global refresh” can be implemented
- PHP /.jsp/.aspx/.asp… And.html, which is a backend server rendering based on Node (note that the original address may be rewritten).
Benefits of server-side rendering
1, is conducive to SEO optimization (the server rendered good content to the client to present, in the page source code can see the binding content, is conducive to the engine included), but the client to do string splicing, presented content is not in the page source code, is not conducive to SEO optimization
2, as long as the server side has a strong ability to resist pressure, the use of server-side rendering page loading speed will be faster than the client side rendering many large websites (for example: The content of the first screen is rendered on the server side. The client side directly presents the XML data after acquiring it, which increases the speed of opening the page for the first time. The content of the remaining screen is rendered on the client side through data splicing based on AJAX
AJAX operation
Create an instance of XMLHttpRequest
let xhr=new XMLHttpRequest();
//=>IE6 is incompatible, using new ActiveXObject to implement
let xhr=new ActiveXObject();
Copy the code
Open the request
//=> Open request: Some configuration items before sending a request
xhr.open([HTTP METHOD],[URL],[ASYNC],[USER-NAME],[USER-PASS]);
Copy the code
URL
Address of the Application Programming Interface (API) that sends requests to the server
ASYNC
Set synchronous asynchrony for AJAX requests. The default is asynchrony (true for asynchrony) and false for asynchrony. Asynchronous programming is used in projects to prevent blocking subsequent code execution
USER-NAME/USER-PASS
User name and password
HTTP request mode
GET: GET data from the server (give less and GET more)
POST: Push data to the server (give more and get less)
DELETE: DELETE something from the server (usually some files)
HEAD: Only the response header returned by the server, not the content in the body
PUT: To PUT something (usually a file) on a server (post series)
The OPTIONS: It is typically used to send a probing request to the server, and if the server returns a message indicating that the current client has established a connection with the server, we can proceed with other requests. (TRACE does this, but axios, the AJAX library, does this when making cross-domain requests, If you can connect to the server, you will continue to send other requests.
TRACE
CONNECT
All requests can pass content to and from the server side
GET and POST
1, : the way of transmitting information to the server is different
- GET is based on the URL address
Question marks the participation
To pass information to the server
xhr.open("GET"."/temp/list? xxx=xxx&xxx=xxx")
Copy the code
- The POST is based on
Request body
Passing information to the server, basically the client passing information to the server is also a string
let xhr = new XMLHttpRequest();
xhr.open('POST'.'https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/list');
xhr.onreadystatechange = (a)= > {
if(!/^(2|3)\d{2}$/.test(xhr.status)) return;//=> Prove that the server has returned the content (HTTPqing)
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText)); }}; xhr.send(JSON.stringify({id:1000.lx:2000}));//=> The request body is passed to the server in JSON format, but the real project is commonly used in urL-encode format "id=1000&lx=2000"(in order to ensure the same format as GET, both are in the form of question mark parameter, but one in the URL, one in the send);
Copy the code
GET is usually used to fetch (less to the server), while POST is used to send a lot to the server. If POST is based on the question mark method, there will be some problems: THE URL will be long concatenation, and the browser has a maximum length of URL (Google 8KB, Firefox 7KB, IE2KB…). So GET requests can be passed based on THE URL, while POST is passed using the request body (there is no limit to the request body in theory. In real projects, we will set the size limit ourselves to prevent the request from being delayed due to uploading too much information).
2, : GET is not secure, and POST is relatively secure
- Because GET transmits information to the server based on “question mark parameter”, it is easy to be URL hijacked by hackers
- POST is delivered based on the request subject, which is relatively difficult to be hijacked. Therefore, we should use POST requests for security interactions such as login and registration.
3, : GET produces an uncontrollable cache, POST does not
Uncontrollable: not want it, want it, don’t want it, this is the browser memory cache, we can’t control based on JS, real project we kill this cache
A GET request is cached because the browser will retrieve the data from the cache if the request is sent repeatedly to the same address (with the same parameter information).
The solution
xhr.open("GET",`/temp/lsit? lx=1000&_=${Math.random()}`); //=> Ensure that the address of each request is not exactly the same: append a random number to the end of each request (use _ as attribute name to avoid conflict with other attribute names)Copy the code
The example completes an AJAX request based on JS, requiring that the latest data be retrieved from the server every 10 seconds to be displayed on the page
Interface address: /custom/list Request method: GET Pass identifier: type = chengjiao Return result: [{id:1.name:'Joe'},... ] -----------------------let queryData=function(){
let xhr=new XMLHttpRequest();
xhr.open("get".`/custom/list? type=chengjiao&_=The ${Math.random()}`.true);
xhr.onreadystatechange=function(){
if(xhr.readyState===4 && xhr.status===200) {//=> The response body is returned to the client, and the request is successfully sent
let data=JOSN.parse(xhr.responseText);
}
}
xhr.send(null);
}
let autoTimer=setInterval(queryData,10000);
Copy the code
3. Event monitoring
The readyStatechange event (AJAX statechange event), which is triggered whenever the AJAX state changes, is listened for. Based on this event, the response header returned by the server can be retrieved. The response header returns faster than the response body
xhr.onreadystatechange=()=>{
if(xhr.readyState===4 && xhr.status===200){ xhr.responseText; }};Copy the code
AJAX state
'0' : UNSENT just created XHR, has not yet sent '1' : OPENED already performed the OPEN operation '2' : HEADERS_RECEIVED Already sent AJAX request (AJAX task started), the response header is already received by the client (the response header contains: Server time, HTTP status code returned...) '3' : LOADING the response body is returning '4' : DONE The response body has been received by the clientCopy the code
Regardless of whether the request succeeds or fails (the HTTP network status code), the four steps of AJAX, that is, the entire status code, must be traversed once
Status (HTTP network status code)
The result and cause of the current interaction can be clearly reflected according to the status code
200: OK, success (only to prove that the server successfully returned information, but not necessarily the information your business needs)
301: Moved Permanently transferred
- Domain name change, access to the original domain name is redirected to the new domain name, for example, jingdong original domain name is www.360buy.com, if you enter this domain name will directly jump to the existing domain name www.jd.com
302: Move temporarily
- Generally used as a server load balancer: When a server reaches the maximum number of concurrent requests, the subsequent users are temporarily transferred to other server groups for processing
- Occasionally a real project will put all images on a separate “image processing server” to reduce the stress on the master server, which will transfer the images to the image server when the user accesses them
307: temporary redirect
- The site now operates over HTTPS, and if the user accesses HTTP, they will be redirected to HTTPS based on 307
304: Not Modified Sets the cache
- For resource files that are not frequently updated, such as CSS/JS/HTML/IMG, the server will set the 304 cache with the client. After loading these resources for the first time, they will be cached to the client. When obtaining them next time, they will be obtained from the cache. If the resource is updated, the server will force the client to pull it from the server by last changing the time. With CTRL+F5 forcing the page refresh, the cache 304 does is useless
400: Bad Request Request parameters are incorrect
401: Unauthorized Access Is unavailable
404: NOT Found resource
413: Request Entity Too Large The content resources interacting with the server exceed the maximum limit of the server
500: Internal Server Error Unknown Server Error
503: Service Unavailable The server is overloaded
4. Send AJAX requests
From this step, the current AJAX task starts. If AJAX is synchronous, subsequent code does not execute until the AJAX state is successful, whereas asynchronous code does not
Xhr.send ([request body content])//=> Start from this step The AJAX task has just begunCopy the code
Case problem
let xhr=new XMLHttpRequest();
xhr.open('GET'.'/temp/list'.true);//=>readystate===1
xhr.onreadystatechange=(a)= >{
if(xhr.readyState===2) {console.log(1); }if(xhr.readyState===4) {console.log(2);}
};
xhr.send();The onreadyStatechange event is triggered when the value of readyState changes. When the value of readyState changes from 1 to 2, the method bound to the event is executed. If the value of readyStatechange changes from 1 to 2, the method bound to the event is executed. From 3 to 4, the event is fired and the method is executed, output 2
console.log(3);
//=> output 3,1,2
Copy the code
let xhr=new XMLHttpRequest();
xhr.open('GET'.'/temp/list'.true);//=>readystate===1
xhr.send();//=> The onreadyStatechange event will be triggered if the value of readyState changes, and the onreadyStatechange event will be triggered. When changing from 1 to 2, the event-bound method executes, prints 1, changes from 2 to 3 methods are also executed, but there is no corresponding output, changes from 3 to 4, the event is fired and the method is executed again, prints 2
xhr.onreadystatechange=(a)= >{
if(xhr.readyState===2) {console.log(1); }if(xhr.readyState===4) {console.log(2);}
};
console.log(3);
//=> output 3,1,2
Copy the code
let xhr=new XMLHttpRequest();
xhr.open('GET'.'/temp/list'.false);/ / = > readystate = = = 1, synchronization
xhr.onreadystatechange=(a)= >{//=> Bind the event asynchronously and put it into the waiting task queue
if(xhr.readyState===2) {console.log(1); }if(xhr.readyState===4) {console.log(2);}
};
xhr.send();//=> The onReadyStatechange event is triggered whenever the readyState value changes. The main task queue is occupied by AJAX tasks, so the onreadyStatechange event trigger method can be executed in the main task queue until the readyState changes to 4, and output 2. The entire AJAX task is completed and then output 3 in the main task queue
console.log(3);
//=> output 2,3
Copy the code
let xhr=new XMLHttpRequest();
xhr.open('GET'.'/temp/list'.true);/ / = > readystate = = = 1, synchronization
xhr.send();Onreadystatechange: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async: async At this point, readyState is already 4 and will not change, so the event will not be triggered at all and will only output 3
xhr.onreadystatechange=(a)= >{
if(xhr.readyState===2) {console.log(1); }if(xhr.readyState===4) {console.log(2);}
};
console.log(3);
/ / 3 = > output
Copy the code
Attributes and methods about XHR
` XHR. Response ` : response body content ` XHR. The responseText ` : the content of the response body is string ` XHR. The responseXML ` : XML document object is the content of the response body ` XHR. Status ` : The returned HTTP status code 'xhr.statusText' : description of the status code 'xhr.timeout' : sets the timeout time of the requestCopy the code
let xhr = new XMLHttpRequest();
xhr.open('GET'.'temp.json');
xhr.timeout=200;
xhr.ontimeout=function(){
console.log("Request timed out. Please try again later.");
};
xhr.onreadystatechange=function(){
if(xhr.readystate===4 && xhr.status===200) {}}Copy the code
` XHR. WithCredentials ` : whether to allow cross-domain (FALSE) ` XHR. The abort () ` : forced interrupt request ` XHR. The getAllResponseHeaders () ` : Get all response headers' xhr.getresponseHeader ([key]) ': Get the response header corresponding to the key, for example: Xhr.getresponseheader ("data") is the server time in the response, but the result is Greenwich mean time and is a stringCopy the code
xhr.onreadystatechange=function(){
if(xhr.readyState===2) {//=> The response header is already back
let time=xhr.getResponseHeader("date");//=> The Greenwich mean time is a character string
new Date(time);//=> Format the specified time string as standard Beijing time. It is no longer a string, but an instance of the Date class, which is also standard time format data
}
if(xhr.readyState===4) {console.log(xhr.responseText); }}; xhr.send(null);
Copy the code
'xhr.open()' : opens the URL request 'xhr.overridemimeType ()' : overwrites the MIME type 'xhr.send()' : sends the AJAX request 'xhr.setrequestheader ()' : sets the request headerCopy the code
The set request header cannot appear in Chinese and must be set after open
#### Rewrite AJAX methods like jQuery
(function(){
function AJAX(options){
return new init(options);
}
let init=function init(options){
let {
url,
method="get",
data,
dataType="json".async=true,
cache=true,
success,
error
}=options;
["url"."method"."data"."dataType"."async"."cache"."success"."error"].forEach((item) = >{
this[item]=eval(item);
});
this.sendRequest();
}
AJAX.prototype={
constructor:AJAX,
sendRequest:function(){
let queryData=function(){
this.handleData();
this.handleMethod();
this.handleCache();
return new Promise((a)= >{
let {url,method,async,data}=this
let xhr=new XMLHttpRequest();
xhr.open(url,method,async);
xhr.onreadystatechange=function(){
if(xhr.readystate===4) {if(/^(2|3)\d{2}$/.test(xhr.status)){
let result=this.handleDataType(xhr);
success && success(result);
}else{
error && error(xhr,xhr.statusText);
}
}
}
})
}
queryData();
},
handleData:function(){
let str=` `;
if(typeof data==="object") {for(let key in data){
if(! data.hasOwnProperty(key))return;
str+=`${key}=${data[key]}& `;
}
this.data=str.substring(0,str.length- 1); }},handleMethod:function(){
let {url,data,method}=this,
reg=/^(get|head|options|trace|connect)$/i;
if(reg.test(method)){
url.indexOf("?") >0? url+=` &${data}`:url+=`?${data}`;
this.url=url;
this.data=null; }},handleCache:function(){
let {url,cache}=this;
if(/^get$/i && cache===false){
url.indexOf("?") >0? url+=` & _ =The ${+ (new Date()}`:url+=`? _ =The ${+ (new date())}`;
this.url=url; }},handleDataType:function(xhr){
let {dataType}=this,
result=xhr.responseText;
dataType=dataType.toUpperCase();
switch (dataType){
case:"json":
result=JSON.parse(result);
break;
case:"text":
break;
case:"xml":
result=xhr.responseXML;
break;
}
return result;
}
}
init.prototyoe=AJAX.prototype;
window.ajax=AjAX; }) ()Copy the code
axios
Definition: AXIos is an AJAX library based on Promise management that results in an object
let promise = axios.get('A', {
params: {
lx: 12}}); promise.then((result) = >{
console.log(result);
})
Copy the code
Request: create an instance of AJAX. Status: status code. StatusText: description of the status code. Config: Configuration items made based on AXIOS when the request is sentCopy the code
A get or POST request returns a Promise instance, so you can use this to solve the callback region problem
axios.get('A', {
params: {
lx: 12
}
}).then(result= > {
return axios.post('b', {name:12.age:8
});
}).then(result= > {
console.log(result);
});
Copy the code
Support for separate corresponding request methods
Requests are sent based on GET
The content of the question mark parameter can be passed as an object based on the params property in the configuration item, or can be concatenated directly after the URL
axios.get('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/info?name=23', {
params: {
lx: 12}})Copy the code
The headers returned will have Query String Parameters
Parameter transmission based on POST
The first parameter is the URL address, the second is the request body (object format), and the third is other configuration items. The request body sends RAW(JSON format string) to the server, not X-www-form-urlencoded
axios.post('a', {name:12.age:8
});
Copy the code
So the headers that’s going to be returned has the Request Payload and it stores the Payload that’s going to be sent in
Axios provides
All methods
You can simply do several requests and then do something else, and get the result of the request together, and return it as an array, with each item in the array corresponding to the object returned by each request
let sendAry = [
axios.get('A'),
axios.get('B'),
axios.post('C')]; axios.all(sendAry).then(result= > {
console.log(result);//=>result is an array
let [resA, resB, resC] = result;
});
Copy the code
The corresponding AXIos has a spread method, which can structure the returned result into a single result. The principle is based on the kerochemical function in JS, similar to the source of bind method
let sendAry = [
axios.get('A'),
axios.get('B'),
axios.post('C')]; axios.all(sendAry).then(axios.spread((resA,resB,resC) = >{
console.log(resA, resB, resC);//=> Respectively represent the results of three requests})) -- -- -- -- -- -- -- --//=> spread source in axios library
module.exports = function spread(callback) {
return function wrap(arr) {//=>arr =>arr;
return callback.apply(null, arr);
};
};
//=>spread (); //=>spread (); //=>spread (); //=>spread (); //=>spread (); Execute the callback function
Copy the code
Method of initializing common configuration items in AXIOS
baseURL
Set baseURL so that the URL passes directly to the following path for later use
axios.defaults.baseURL="https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp"
----
axios.get("/list", {params: {lx:12}})Copy the code
Set up the response interceptor
Do some intercepting when the request succeeds or fails (methods in the interceptor are executed before successful methods are executed)
Principle: After the promise then method, then click then success to request success to do something (source code)
axios.interceptors.response.use(function success(result){
return result.data;//=> is equivalent to passing the contents of the response body (data return) in the result (object) returned by the successful request as an argument to the method to execute in then
})
Copy the code
Sets the request header and request body
The format used to send content to the server in a POST request based on the request body. The default is RAW, and the x-www-URL-encoded format is commonly used in projects
Both must be set at the same time to take effect, and only for the POST method. The GET method, Query String Parameters, is returned as an object
axios.defaults.headers["Content-Type"] ="appliction/x-www-form-urlencoded";
axios.defaults.transformRequest=function (data){//=>data is the content of the request body in the POST
let str=` `;
for(let attr in data){
if(! data.hasOwnProperty(attr))break;
str+=`${attr}=${data[attr]}`
}
return str=str.substring(0,str.length- 1);
}
Copy the code
Set the success failure rule
The default status code in AXIos starts with 2 as success, and we can customize the rules for success and failure
axios.defaults.validateStatus=function validateStatus(status){
return /^(2|3)\d{2}$/.test(status)
}
Copy the code
Rewrite part of the axios source code
(function(window){
let _defaults={
url:"".baseURL:"".method:"get".headers: {},data:null.//=> Request body of the POST series requests
params:null.//=> The question mark parameter of the get series
dataType:"json".cache:ture//=> Whether to create cache
}
function axiosAJAX(options){
let {method,url,baseURL,headers,data,params,dataType,cache}=options;
//=> Process params and data according to method
let reg=/^(get|head|delete|options|trace|connect)$/i;
if(reg.test(method)){
if(typeof params==="object"&& params! = =null) {let str=` `;
for(let key in params){
if(! params.hasOwnProperty(key))break;
str+=`${key}=${params[key]}& `;
}
params=str.substring(0,str.length- 1);
}
url.indexOf("?") >- 1? url+=`&{params}`:url+=`? {params}`;
data=null;
}else{
if(typeof data==="object"&& data! = =null) {let str=` `;
for(let key in data){
if(! data.hasOwnProperty(key))break;
str+=`${key}=${data[key]}& `;
}
data=str.substring(0,str.length- 1); }}// if false, do not create cache
if(cache===false && reg.test(method)){
url.indexOf("?") >- 1? url+=` & _ =The ${new Date().getTime()}`:url+=`? _ =The ${new Date().getTime()}`;
}
return new Promise((resolve,reject) = >{
let xhr=new XMLHttpRequest();
xhr.open(method,`${baseURL}${url}`);
for(let key in headers){
if(! headers.hasOwnProperty(key))break;
if(/[\u4e00-\u9fa5]/.test(headers[key])){
headers[key]=encodeURIComponent(headers[key])
}
xhr.setRequestHeader(key,headers[key]);
}
xhr.onreadystatechange=function(){
if(xhr.readyState===4) {if(/^(2|3)\d{2}$/.test(xhr.status)){
let result=xhr.responseText;
dataType=dataType.toUpperCase();
dataType==="JSON"? result=JSON.parse(result):(dataType==="XML"? result=xhr.responseXML:null);
resolve(result);
}else{
reject(xhr);
}
}
}
xhr.send(data);
});
}
axiosAJAX.defaults=_defaults;//=> You can modify the default configuration items
/ / = > get series
["get"."head"."delete"."options"."trace"].forEach((item) = >{ options={... defaults,... options,url:url,method:item};
return axiosAJAX(options);
});
/ / = > post series
["post"."put"].forEach((item) = >{ options={... _defaults,... options,url:url,method:item,data:data};
return axiosAJAX(options);
})
window.axiosAJAX=axiosAJAX; }) (window)
Copy the code
fetch
Fetch is a new API in ES2018 specification. It is a built-in API in JS. Based on FETCH, information communication between client and server can be realized
fetch('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/info', {
method: 'GET'.headers: {//=> Set the request header
'content-type': 'x-www-form-urlencoded'
},
//=> Both same-origin and cross-domain requests carry COOKIE information
credentials: 'include'
})
Copy the code
Use FETCH to send requests
- BODY cannot be set for requests such as GET/HEAD
- Regardless of the state returned by the server, fetch is not considered a failure (even if it is a state code starting with 4 or 5), it executes the method in THEN (which requires our own exception throwing), and the argument received by the then callback is not a result, but an instance of Response. We need to invoke methods on its prototype to get the results we need from the server
fetch('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/add', {
method: 'post'.body: 'a=1&b=2'//=> Only strings are supported in BODY (GET request cannot set BODY yet, GET request must be manually added to the end of url via question mark)
}).then(result= > {
console.log(result);
let {status} = result;
if (/^(4|5)\d{2}$/.test(status)) {//=> Throw an exception
throw new Error('query data is error! ');
return;
}
return result.json();//=> This is the result we want from the server side
}).then(result= > {
console.log(result);
}).catch(msg= > {
console.log(msg);
});
Copy the code
header
redirected
status
statusText
type
url
ArrayBuffer ()/blob()/json()/text() : Methods of getting data from the server