Front-end interview FAQ:
http method
-
HTTP1.0 defines three request methods: GET, POST, and HEAD
-
HTTP1.1 adds five new request methods: OPTIONS, PUT, PATCH, DELETE, TRACE, CONNECT
http status code
A 2 header (request successful) indicates that the request's status code was successfully processed. 200 (Success) The server has successfully processed the request. Typically, this means that the server has provided the requested web page. 201 (Created) The request succeeded and the server created a new resource. 202 (Accepted) The server has accepted the request but has not yet processed it. 203 (Unauthorized Information) The server has successfully processed the request, but the information returned may come from another source. 204 (No content) The server successfully processed the request, but did not return any content. 205 (Reset Content) The server successfully processed the request, but did not return any content. 206 the server successfully processed some OF the GET requests. A 3 header (the request was redirected) indicates that further action is required to complete the request. Typically, these status codes are used for redirects. 300 (Multiple options) The server can perform a variety of operations on a request. The server can select an operation based on the requester (User Agent) or provide a list of operations for the requester to select. The page for request 301 (Permanent move) has been permanently moved to a new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location. The 302 (temporary mobile) server currently responds to requests from web pages in different locations, but requesters should continue to use the original location for future requests. 303 (View other locations) The server returns this code when the requester should use a separate GET request for a different location to retrieve the response. 304 (Unmodified) The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned. 305 (Using a proxy) The requester can only access the requested web page using a proxy. If the server returns this response, it also indicates that the requester should use a proxy. 307 (temporary redirection) The server currently responds to requests from web pages in different locations, but the requester should continue to use the original location for future requests. These status codes indicate that the request may be in error, preventing the server from processing it. 400 (Error request) Server does not understand the syntax of the request. The 401 (unauthorized) request requires authentication. The server may return this response for a web page that requires login. 403 (Forbidden) The server rejects the request. 404 (Not found) The server could not find the requested page. 405 (method disable) Disables the method specified in the request. 406 (Not accepted) Web pages that cannot respond to a request using the requested content feature. 407 (Proxy authorization required) This status code is similar to 401 (unauthorized), but specifies that the requester should authorize the use of the proxy. 408 (Request Timeout) The server timed out while waiting for a request. 409 (Conflict) A server conflict while completing a request. The server must include information about the conflict in the response. 410 (Deleted) The server returns this response if the requested resource has been permanently deleted. 411 (Valid length required) The server will not accept requests that do not contain a valid content length header field. 412 (Conditions not met) The server does not meet one of the conditions set by the requester in the request. 413 (Request entity too large) The server cannot process the request because the request entity is too large for the server to handle. 414 (Request URI too long) The request URI (usually the url) is too long for the server to process. 415 (Unsupported media Type) The requested format is not supported by the requested page. 416 (Requested scope not required) If the page cannot provide the requested scope, the server returns this status code. 417 (expected value not met) The server is not met"Hope"Request header field requirements. These status codes indicate that an internal error occurred while the server was trying to process the request. These errors may be server errors rather than request errors. 500 (Server internal error) The server encountered an error and could not complete the request. The 501 (not yet implemented) server does not have the capability to complete requests. For example, the server may return this code if it does not recognize the request method. 502 (Error Gateway) server, acting as gateway or proxy, received invalid response from upstream server. 503 (Service unavailable) The server is currently unavailable (due to overloading or downtime for maintenance). Usually, this is a temporary state. 504 (Gateway Timeout) The server acted as a gateway or proxy, but did not receive the request from the upstream server in time. 505 (HTTP version not supported) The server does not support the HTTP protocol version used in the request.Copy the code
The cache
- Client cache
- Proxy server cache
- How does the cache verify availability
Cache-control:
- Max-age =100 Static resource cache 100 seconds
- Public and private Settings can only be cached on the client side or through a proxy server
- Must-revalidate Must be verified on the server before the cache can be used
- No-cache and no-store control whether to use cache
Cache validation
last-modified
Cooperate withif-modified-since
etage
Cooperate withif-none-match
Caching is one of the biggest performance improvements in Web development
More meaningful head
Content-type
,Content-Encoding
And so on are used to constrain data typescookie
Hold session informationCORS
Implement cross-domain and maintain security restrictions
Digging deeper into TCP:
- What is a three-way handshake
- How to create HTTPS links, and why is HTTPS secure
- What are long links and why are they needed
- Why does HTTP2 channel multiplexing improve performance
The input
URL
The complete process of returning a post-HTTP request
- Redirect: The browser records the redirect to a new address permanently. What is the redirect to
- 2. See cache: See if the requested resource has been cached
- 3. DNS resolution
- 4. Create a connection
- 5. Start sending packets
Nginx
- Configure ngniX as the HTTP proxy
- Enable the caching function of NgniX
- Leverage proxy caching to improve HTTP performance
HTTP protocol foundation and development history
Introduction to the five layer network model
- Physical layer: mainly define how physical devices transmit data, hardware devices
- Data link layer: resume data link links between communicating entities
- Network layer: Creates logical links for data transfer between nodes
- Transport layer: To provide reliable end-to-end services to users, the transport layer hides the details of lower-level data communication from higher levels
- Application layer: Provides many services for applications built on top of TCP and hides the details of network transport
HTTP protocol history
The HTTP 0.9
- 1. There is only one command GET
- 2. No data description such as header is provided
- 3. The server closes the TCP connection after sending the packet
HTTP1.0
- 1. Added a lot of commands
- 2. Add status code and header
- 3. Multi-character set support, multi-part sending, permissions, caching, etc
HTTP1.1
- 1, persistent connection (establish TCP consumption)
- 2, Pipeline (the same link can send multiple requests, the server is in order to accept, may need to wait, serial)
- Add host and other commands
HTTP2 (not yet universal)
- 1. All data is transmitted in binary
- 2. Multiple requests sent within the same link are no longer ordered (parallel)
- 3. Header information compression and push functions to improve efficiency
The HTTP three-way handshake
- The client and server need to create a TCP-connetion to send messages
- HTTP has no connection, only request and response, which are packets
- TCP links can send multiple HTTP requests
Sequence diagram of three handshakes
URI – URL and URN
Uniform Resource Locator/ Uniform Resource Locator
http://user:[email protected]:80/path?query=string#hash
Copy the code
URN: Permanent Uniform resource locator
- It can still be found after the resource has moved
- At present, there is no very mature use scheme
HTTP Packet Format
An overview of HTTP features
Restriction and resolution of CORS cross-domain requests
The request has been sent and the returned data has been retrieved. However, when the browser parses back, it finds that it is not allowed. The browser intercepts and hides the data. The server must allow spanning requests.
-
Browsers allow link, script, img, etc., to be loaded across write paths on tags, regardless of whether the server allows cross-domain requests. Jsnop works the same way
-
On the server, you can add: ‘access-Control-allow-origin ‘: ‘*’ to Allow cross-domain Access. The ‘*’ indicates that all cross-domain access is allowed. You can set the specified server access. Multiple domains can be determined dynamically
CORS cross-domain constraints and pre-request validation
Restrictions that do not require pre-request: (The rest need pre-request validation before being sent)
- 1. Method allowed:
GET
,HEAD
,POST
- 2, allows
Content-Type
:text/plain
,multipart/form-data
,application/x-www-form-urlencoded
- 3. Request header restriction:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type
: Is limited to three valuesapplication/x-www-form-urlencoded
,multipart/form-data
,text/plain
- 4,
XMLHttpRequestUpload
The object army did not register any event listeners - 5. Not used in the request
ReadableStream
Solutions:
'Access-Control-Allow-Origin': 'http://127.0.0.1:8888'.'Access-Control-Allow-Headers': 'X-Test-Cors'.'Access-Control-Allow-Methods': 'POST, PUT, DELETE'.'Access-Control-Max-Age': '1000'// The amount of time a pre-request is allowed to be sent in this manner, during which no further pre-requests need to be sentCopy the code
The cache firstCache-Control
The meaning and use of
The cache can be
pulic
:http
Any path the request takes can be cached for the returned contentprivate
: Only the browser that initiated the request can cachenon-cache
: No node can be cached
Due to:
max-age=<seconds>
s-maxage=<seconds>
// If both are set, the proxy server will read this, set specifically for the proxy servermax-stale=<seconds>
// Only the originator setting works, even thoughmax-age
Expired, as long as themax-stale
Expired caches can still be used in time, and Settings in server return have no effect
Revalidate:
- 1.
must-revalidate
// If the max-age has expired, the request must be sent to the original server to obtain data again to verify whether the expiration is true - 2,
proxy-revalidate
// In the cache server - 3,
no-store
// Always go to the server for a new one - 4,
no-transform
// Tell the proxy server that the content cannot be changed
The cache-control application
- 1. It is declarative and not binding
- 2,
chrome
The inside of thedisable cache
Must dash out - 3,
cache-control
It is a client cache, and generally the cache time is relatively long, may cause static resource changes on the server and the client cannot update. Solution: Add a string of hash codes to the static resource file. If the content does not change and the hash code does not change, you can use the static resource cache. If the file has edges, the request is a new static resource request.
'Cache-Control': 'max-age=200,public'
Copy the code
Cache validationLast-Modefied
和Etag
The use of
Resources to verify
last-modified
- Last modified time
- Cooperate with
If-Modified-Since
orIf-Unmodified-Since
use
Etag
- More rigorous verification
- Data signatures (any modification, unique) are typically hashed to obtain unique values
- Cooperate with
If-Match
orIf-Non-Match
- Determine whether to use caching by comparing the signature of the resource
instructions
- 1.
304:Not Modified
. The resource is not modified and can be read directly from the cache. ignoreresponse body
The contents of it. - 2,
If-Modified-since
andIf-None-Match
.disable cache
The cache validation header does not send these two parameters. - 3. If set
no-store
I’m going to ignore anything that has to do with caching
const http = require('http')
const fs = require('fs')
http.createServer(function(request, response) {
console.log('request ', request.url)
const html = fs.readFileSync('test.html'.'utf8')
if (request.url === '/') {
const html = fs.readFileSync('test.html'.'utf8')
response.writeHead(200, {
'Content-Type': 'text/html'
})
response.end(html)
}
if (request.url === '/script.js') {
const html = fs.readFileSync('test.html'.'utf8')
const etag = request.headers['if-none-match']
if (request.getHeader = '777') {
response.writeHead(304, {
'Content-Type': 'text/javascript'.'Cache-Control': 'max-age=2000000,no-cache'.'Last-Modified': '123'.'Etag': '777'
})
response.end('123')}else {
response.writeHead(200, {
'Content-Type': 'text/javascript'.'Cache-Control': 'max-age=2000000,no-cache'.'Last-Modified': '123'.'Etag': '777'
})
response.end('console.log("script loadded")')
}
}
}).listen(8888)
console.log('serve listening on 8888')
Copy the code
const http = require('http')
const fs = require('fs')
http.createServer(function(request, response) {
console.log('request ', request.url)
const html = fs.readFileSync('test.html'.'utf8')
response.writeHead(200, {
'Access-Control-Allow-Origin': The '*'.'Access-Control-Allow-Headers': 'X-Test-Cors'
})
response.end(html)
}).listen(8887)
console.log('serve listening on 8887')
Copy the code
cookie
和 session
cookie
- through
Set-Cookie
Settings, in the domain request - The next request will be picked up automatically
- You can set multiple key-value pairs
Cookie attribute
max-age
和expires
Set the expiration time (if you don’t set the expiration time, the browser is closed)secure
Only in thehttps
When senthttpOnly
Unable to getdocument.cookie
access
'Set-Cookie': ['id=12343,max-age=10,name=dafdafda'; HttpOnly]Copy the code
Cookies cannot be obtained in different domains. Secondary domain names of the same primary domain name can share cookies through domain.
'Set-Cookie': ['id=12343,max-age=10,domain="test.com']
Copy the code
Long HTTP connection
- reuse
TCP/IP
The connection - The cost of a three-way handshake is probably no higher than the cost of a long connection
Connection: keep-alive
chrome
Generally six concurrent processesHTTP2
Channel multiplexing
Data consultation
request
Accept
: // Returns the data typeAccept-Encoding
// How to compress dataAccept-Language
:// Return languageUser-Agent
: // Return to PC or mobile
return
Content-type: corresponding to Accept content-Encoding: corresponding to accept-encoding content-language: corresponding to accept-languageCopy the code
X-content-type-options :nosniff // Does not proactively predict returned ContentCopy the code
Data compression
const zlib = require('zlib')
'Content-Encoding':'gzip'
Copy the code
Redirect
301 Moved Permanently, the requested resource has been Permanently Moved to a new location, and any future references to this resource should use one of the urIs returned by this response. If possible, clients with link editing capabilities should automatically change the requested address to the one that is returned from the server. Unless otherwise specified, the response is also cacheable. Redirects are in the browser cache, and if the user does not clear the cache, the server has no control
The resource requested by 302 Found now temporarily responds to the request from a different URI. Since such redirects are temporary, the client should continue to send future requests to the original address. The response is cacheable only if specified in cache-Control or Expires.
CSP content security policy
The CSP defines the Content-Security-PolicyHTTP header to allow you to create a whitelist of trusted sources so that the browser executes and renders only resources from those sources, rather than blindly trusting everything the server provides. Even if an attacker could find a vulnerability to inject the script, it would not be executed because the source is not included in the whitelist.
role
- Limiting resource access
- Report resource overreach
Limit the way
default-src
Restricts the resource types associated with links globally- Define resource types
Taking instructions
connect-src
: limits what can be loaded through the script interfaceURL
default-src
: Provides backup services for other fetch ordersfetch directives
font-src
: Restricted passage@font-face
Loaded font source.frame-src
: Limit through similar<frame>
and<iframe>
The embedded content source for the tag load.img-src
: Limits image and icon sourcesmanifest-src
: limiting theapplication manifest
Source files.media-src
: Restricted passage<audio>
或<video>
Label loaded media file source.object-src
: Restricted passage<object>
.<embed>
,<applet>
Label loading source.script-src
: Limits javascript sources.style-src
: Limits cascading style sheet file sources.
Document directives: Manage document properties or which policies to apply in the work environment.
base-uri
: will be limited toDOM
The use ofbase
Of the labelURL
plugin-types
: Restriction series can be embedded through some restriction type of resource loadingDOM
The plug-in.sandbox
: Allow similarity{HTMLElement("iframe")}}
sandbox sandbox
attribute
Navigation directives: Navigation directives manage the links that users can open or the links that forms can submit
form-action
: limits the targets that can be used for form submission in a given contextURL
(In plain English, limitsform
theaction
Property link address)frame-ancestors
Specifies a valid parent item that may be embedded in the page<frame>
.<iframe>
.<object>
.<embed>
, or<applet>
navigation-to
Restricted documents can be accessed in any of the following waysURL`` (a, form, window.location, window.open, etc.)
Reporting Instruction section: Reporting instruction controls the reporting process for CSP violations
report-uri
Have the client submit a report when an operation occurs that may violate the CSP. These violation reports are sent to the specified URI in the form of a JSON file via POST requestreport-to
Fires a SecurityPolicyViolationEvent
Other instructions
block-all-mixed-content
Organization uses HTTP to load any resource when a page is loaded using HTTPS.
'Content-Security-Policy:'Default - SRC HTTP: HTTPS' '// Only HTTP and HTTPS loads are allowed'Content-Security-Policy:'default-src \'selt\''; form-action \'self\'// Restrict only linking scripts from outside this siteCopy the code