HTTP and HTTPS
The HTTP protocol: Hyper Text Transfer Protocol is a request and response based, stateless, application layer Protocol, often based on TCP/IP Protocol to Transfer data, the Most widely used network Protocol on the Internet, all WWW files must comply with this standard. HTTP was originally designed to provide a way to publish and receive HTML pages
Communicate between client and server by request >>> response
The disadvantage is not safe enough
HTTP information is transmitted in plaintext without any encryption, which is easy to be intercepted and tampered with by hackers
HTTPS: A transport protocol for secure communication over a computer network. HTTP is used to establish full channels and encrypt data packets using SSL/TLS. The primary purpose of HTTPS is to provide identity authentication to web servers and protect the privacy and integrity of the data exchanged
Based on HTTP, SSL or TLS provides data encryption, identity verification, and data integrity protection
The GET and POST
- From a caching perspective: GET requests are cached by the browser, but POST requests are not
- From the encoding point of view: GET can only urL-encode, only ACCEPT ASCII characters, and POST has no limit
- From the perspective of parameters: GET is generally placed in the URL, so it is not secure, and POST is placed in the body of the request, which is more suitable for transmitting sensitive information
- From an idempotent perspective: GET is idempotent, but POST is not (idempotent means that the same operation is performed and the result is the same)
- From the TCP point of view: GET sends the request packet at one time, while POST is divided into two TCP packets. First, send the header part, and then send the body part if the server responds with 100
HTTP status code
Status codes are classified into five types:
- 1xx: indicates that the protocol processing is in the intermediate state and subsequent operations are required
- 2xx: indicates that the status is successful
- 3xx: Indicates the redirection status. The location of resources changes and a request needs to be made again
- 4xx: The request packet is incorrect
- 5xx: An error occurs on the server
There are several common concrete status codes:
200 OK — Indicates that the request from the client was processed normally on the server
400 Bad Request: indicates that there is a syntax error in the Request packet. If the error occurs, you need to modify the Request content and send the Request again. In addition, the browser treats the status code as if it were 200 OK
401 Unauthorized — An authentication dialog box is required to ask for user information
403 Forbidden – Indicates that access to the requested resource is denied by the server or is not authorized to access it
404 Not Found — The requested resource could Not be Found on the server
500 Internal Server Error – Indicates that the Server has made an Error while executing the request, which may be a bug in the Web application or some temporary failure
502 Bad Gateway – Indicates that a server acting as a Gateway or proxy receives an invalid response from an upstream server, usually not fixed by the client, but by a Web server or proxy server that needs to be fixed
HTTP handles submission of form data
In HTTP, there are two main ways to submit a form. There are two different content-Type values:
- Application/X-www-form-urlencoded: Data will be coded as
&
Delimited key-value pairs with urL-encoded characters - Multipart /form-data: Data is divided into multiple parts, separated by a delimiter. The most important feature is that each form element is an independent resource representation
Cross domain
cookie
In essence, it is a very small text file stored in the browser, which internally stores information in the form of key-value pairs. The disadvantages are small capacity, poor performance, and insecure
An URL
Browsers follow the same-origin policy (same-origin if the Scheme protocol, host host, and port are the same). Non-same-origin sites have the following restrictions:
- Different reads and modifies each other’s DOM
- Do not read and access each other’s cookies, IndexDB, and LocalStorage
- Restricts XMLHttpRequest requests
When the browser sends an Ajax request to the target URL, a cross-domain request occurs whenever the current URL and the target URL are from different sources
How cross-domain requests are handled:
1. CORS, full name for cross-domain resource sharing, requires the common support of browsers and servers
Simple request: An Origin field is automatically added to the request header to indicate which source the request came from. The server takes the request and responds with an access-Control-Allow-Origin field. If Origin is not in the range of the field, the browser intercepts the response
JSONP, although XMLHttpRequest objects follow the same origin policy, the script tag is different. It can use SRC to fill in the target address to issue a GET request, and achieve a cross-domain request and GET the response
3. Nginx is a high-performance reverse proxy server that can be used to easily solve cross-domain problems
XMLHttpRequest
Is the primary Ajax interface for communication between the browser and the server, using multiple protocols (such as File and FTP) to send data in any format (including string and binary)
Ajax involves the following steps:
- 1. Create an XMLHttpRequest instance
- 2. Make an HTTP request
- 3. Receive the data returned by the server
- 4. Update web data
In summary, Ajax makes HTTP requests through the native XMLHttpRequest object, gets the data returned by the server, and then processes it
XMLHttpRequest itself is a constructor that uses the new command to generate an instance without any arguments
var xhr = new XMLHttpRequest();
Copy the code
Instance property of XMLHttpRequest
1, XMLHttpRequest. ReadyState, returns an integer, represent the current state of the instance object. Read-only
- 0, indicating that the XMLHttpRequest instance has been generated, but the instance’s open() method has not yet been called
- 1, the open() method has been called, but the send() method of the instance has not been called. You can still use the setRequestHeader() method of the instance to set the HTTP request header
- 2, indicating that the instance’s send() method has been called and the headers and status codes returned by the server have been received
- 3: indicates that the body part of the data is being received from the server. At this point, if the responseType property of the instance is equal to text or an empty string, the responseText property contains some of the information that was received
- 4: indicates that the data returned by the server is fully received or the data receiving fails
The value of the readyState property changes every time the instance object changes state during communication. Each time this value changes, the readyStateChange event is touched
2, XMLHttpRequest onreadystatechange, pointing to a monitoring function. This property is executed when the readyStatechange event occurs (the instance’s readyState property changes). In addition, the readyState property changes if you abort the XMLHttpRequest request using the instance’s abort() method. To call the XMLHttpRequest. Onreadystatechange property
3, XMLHttpRequest response, said the server returns the data volume (i.e., the HTTP response body part), it can be any data type, such as string, object, binary objects, etc., specific types of XMLHttpRequest. ResponseType attribute decision, read-only
4, XMLHttpRequest. ResponseType, is a string, said the server returns the type of data, this property is writable, can call open () method, called send () method, set the value of this attribute, tell the server to return to specify the type of data. If responseType set to an empty string, is equivalent to the default text XMLHttpRequest. ResponseType attribute can be equal to the following values:
- “(empty string) : Equivalent to text, indicating that the server returns text data
- Arraybuffer: An arrayBuffer object that indicates that the server returns a binary array
- Blob: BLOB object, indicating that the server returns binary objects, such as image files
- “Document” : Document object, indicating that the server returns a document object
- Json: indicates a JSON object
- Text: indicates a character string
5, XMLHttpRequest responseText, return string received from the server, read only; This property does not contain complete data until the HTTP request has been received
6, XMLHttpRequest. ResponseXML, returned from the server receives the HTML or XML document object, read-only. If the request is unsuccessful or the received data cannot be parsed as XML or HTML, this attribute is null. This attribute takes effect only if the content-Type header of the HTTP response is equal to text/ XML or Application/XML. This request before sending a request, the XMLHttpRequest. ResponseType attribute to set as the document. If the content-Type header of the HTTP response is not equal to text/ XML or application/ XML, but you want to get the data from responseXML (i.e., parse the data in DOM format), You will need to manually call the XMLHttpRequest. OverrideMimeType () method, forced to XML parsing
7, XMLHttpRequest. ResponseURL is string, indicates the data sent the server url Note that the value of this attribute and the open () method specified in the request url is not necessarily the same. This property returns the url where the data was actually returned in the event of a server-side jump. In addition, if the original URL contains a fragment, this property will strip the fragment
Xmlhttprequest. status, returns an integer representing the HTTP status code that the server responded to. Generally, the value is 200 if the communication succeeds. If the server does not return a status code, this property defaults to 200. This property is 0 and read-only until the request is issued
9, XMLHttpRequest statusText, return a string, said the state of the server. Unlike the status property, this property contains the entire status information, such as “OK” and “Not Found.” Before the request is sent (that is, before the open() method is called), the value of this property is an empty string; If the server does not return a status prompt, the value of this property defaults to OK. This property is read-only
The xmlHttprequest. timeout property returns an integer indicating the number of milliseconds after the request is terminated if no result is received. If this property is equal to 0, there is no time limit
11, XMLHttpRequestEventTarget ontimeout, property is used to set up a monitoring function, in the event of a timeout event, will carry out the monitoring function
Event listening properties
The XMLHttpRequest object can specify listener functions for the following events:
- XMLHttpRequest. Onloadstart: loadstart events (HTTP requests) to monitor function
- XMLHttpRequest. Onprogress: progress events (is sending and load data) surveillance function
- Xmlhttprequest.onabort: A listener function for the abort event (request abort, for example, when the user calls the abort() method)
- Xmlhttprequest. onError: A listener for error events (failed requests)
- Xmlhttprequest. onload: A listener for the load event (the request completed successfully)
- Xmlhttprequest. onTIMEOUT: A listener for the timeout event (when a user-specified time limit has expired and the request has not completed)
- Xmlhttprequest. onloadEnd: A listener function for the loadEnd event (request completion, regardless of success or failure)
The listener function for the Progress event takes an event object parameter that has three attributes: the Loaded attribute returns the amount of data that has been transferred, the total attribute returns the total amount of data, and the lengthComputable attribute returns a Boolean value indicating whether the progress of the load is computable. Of all these listener functions, only the listener of the Progress event has parameters. The other functions have no parameters
13, XMLHttpRequest withCredentials, is a Boolean value, said cross-domain request, the user information (such as cookies and certification of HTTP headers) is included in the request, the default is false, that is, when sending the cross-domain request to example.com, Cookies that example.com sets on this machine, if any, are not sent
Xmlhttprequest.upload, XMLHttpRequest can send not only requests, but also files, which is called AJAX file upload. After you send the file, you can watch the progress of the upload by viewing an object that you get through the xmlHttprequest.upload attribute. The main method is to listen for various events on this object: loadStart, loadEnd, load, abort, error, progress, timeout
Instance method of XMLHttpRequest
Xmlhttprequest.open (), which specifies the parameters of the HTTP request, or initializes the XMLHttpRequest instance object, which can accept up to five parameters
- Method: indicates the HTTP verb method, such as GET, POST, PUT, DELETE, and HEAD
- Url: specifies the url to which the request is sent
- Async: Boolean value that indicates whether the request is asynchronous. The default value is true. If this parameter is set to false, the send() method does not proceed until the receiving server returns a result
- User: indicates the user name used for authentication. The default value is an empty string and the parameter is optional
- Password: indicates the password used for authentication. The default value is an empty string and is optional
Note that if you use this method again on an AJAX request that used the open() method, you are calling abort(), which terminates the request
Xmlhttprequest.send (), which is used to send an HTTP request with an optional parameter. If no parameter is taken, the HTTP request has only one URL and no data body. If it has a parameter, it contains a body of information that contains specific data in addition to the header information, a typical example being a POST request
Among them, sometimes the parameters in URL need to be encoded, using encodeURIComponent method
Note that all XMLHttpRequest listening events must be set before the call to the send() method, which takes the data to be sent. Data in a variety of formats can be used as its parameters
3, XMLHttpRequest. SetRequestHeader (), is used to set the browser sends the HTTP request header, this method must be in the open (), after send () call before, if the method calls for many times, set the same field, The value of each call is combined and sent as a single value. The method takes two arguments, the first being a string representing the field name of the header information, and the second being the field value
4, XMLHttpRequest. OverrideMimeType (), is used to specify the MIME type, cover the MIME type returned by the server really, so that the browser for different processing. For example, if the server returns data of type TEXT/XML, for some reason the browser fails to parse the data and fails to retrieve the data. To retrieve the raw data, we can change the MIME type to text/plain so that the browser doesn’t parse it automatically and we can retrieve the original text
Note that this method is called before send() to modify the data type returned by the server, which is not what you would normally do. If you want the server to return the specified data type, you can tell the server with the responseType property, as in the following example. Use the overrideMimeType() method only if the server is unable to return a certain data type
5, XMLHttpRequest. GetResponseHeader (), returns the HTTP header information to specify the value of the field, if haven’t received the server response or specified field does not exist, returns null, the method of parameter is not case-sensitive
6, XMLHttpRequest. GetAllResponseHeaders (), returns a string, said all the HTTP header information from the server. The format is a string. Each header is separated by CRLF (carriage return + line feed). If no response is received from the server, this property is null. If a network error occurs, this property is an empty string
Xmlhttprequest.abort (), which is used to abort an ALREADY issued HTTP request. The readyState attribute changes to 4 and the status attribute to 0
Event of the XMLHttpRequest instance
1. ReadyStateChange:
If the value of the readyState property changes, the readyStateChange event will be triggered. You can specify the listener function of this event to handle different states, especially if the state changes to 4, indicating that the communication is successful. The callback function can then process the data sent back from the server
2. Progress Event:
When a file is uploaded, both the XMLHttpRequest instance object itself and the instance’s Upload property have a progress event that continuously returns the progress of the upload
Load event, error event, ABORT event
The load event indicates that data from the server is received, the ERROR event indicates that the request failed, and the abort event indicates that the request is interrupted (for example, when the user cancellations the request).
4. Loadend:
Abort, Load, and ERROR are accompanied by a loadEnd event, indicating that the request ends without knowing whether it succeeded
5, Timeout event:
A timeout event is emitted when the server does not return a result after the specified time
A Blob object
Blob objects represent the data contents of a binary file, such as the contents of an image file, which can be read and written from Blob objects. It is commonly used to read and write files, and its name is short for Binary Large Object
Browsers natively provide the Blob() constructor, which generates instance objects
new Blob(array [, options])
Copy the code
The Blob constructor takes two arguments. The first is an array of strings or binary objects representing the contents of the newly generated Blob instance object. The second argument, which is optional, is a configuration object that currently has only one property, Type, whose value is a string representing the MIME type of the data. The default is an empty string
Instance properties and instance methods
Blob has two instance attributes size and type that return the size and type of the data, respectively
Blob has an instance method slice that copies the original data and returns an instance of the Blob
The Slice method takes three parameters, all of which are optional. These, in turn, are the starting byte position (default: 0), the ending byte position (default: the value of the size property, which itself will not be included in the copied data), and the data type of the new instance (default: empty string)