- An Overview of HTTP Requests & Cross-Origin Resource Sharing (CORS)
- Bilge Demirkaya
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: zenblo
- Proofread: PassionPenguin, regon-cao
This section describes HTTP request and cross-domain resource sharing CORS
Introduction of the URL
The following sample URL consists of four parts:
Scheme Specifies the Protocol to be used. The protocol specifies how data is transferred and how requests are handled. You can get a good idea of what this URL is for when you look at the protocol. (Such as email protocols with SMTP, POP3, IMAP, SSH requests to get and manage git repositories, or HTTP requests for the Web.)
HTTP – runs on port 80 by default, which specifies the header in the request.
HTTPS – Similar to HTTP, but considered secure communication between browser and server. It differs from HTTP:
- The default runs on port 443
- Encrypts all request or response headers except IP requests
Host name:
It’s just a better named IP address.
Path:
The URL path is like your directory path. It provides the user and the search engine with a section to know where they are currently, such as the/About section. This helps achieve better search engine optimization (SEO).
Query parameters:
It is used to send data to the server. It is often used for marketing reasons to see the effectiveness of advertising. In order to? To start, separate the data with &.
Note: For security reasons, it is not recommended to send data with query parameters (so that everyone can see them), and it has a character limit (2048 characters or less).
There are other ways to send data to the server using the HTTP and HTTPS protocols.
Request and Response
When a user enters a domain name into the browser, the browser finds the server (which is just someone else’s computer) and sends a request to the server. If it succeeds in getting a response from the server, it renders the corresponding page on the browser.
Note: The process is the same when you use a terminal to send a request (such as running Node index.js). You don’t need a browser to send a request to the server; you can also use a terminal. However, if the response is HTML, then the terminal doesn’t do anything, because HTML is just a browser directive.
Header section
Both browsers and servers need a lot of information about each other before they can identify each other and ultimately send a request or response. Such as IP addresses, content-types, cookies,Cache-controlAnd so on. You can find it hereA complete listThey carryheaderThe data isKey/value pair.
When sending requests, only two table headers need to be set manually: content-Type and Authorization. Although you can set other table headers, they are usually handled automatically by the browser.
Content-type – When you send data to the server via the body (POST, PATCH, PUT request), you need to specify the Content Type. It can be Application /json, Text/HTML, image/ GIF, or video/mpeg.
Authorization – This is what the server uses to identify users. Unlike the cookie header, this must be set manually by the developer when the request is sent. Typically used for API requests and JWT authentication.
The request processing
Each request sent over the Internet consists of two required sections and one optional section.
- Request line: consists of request methods (GET, POST, DELETE, etc.) and paths (extracted from the URL).
- This has been briefly explained above.
- Request body (Optional) : When you send a POST, PUT, or PATCH request to the server, you need to send a request body packet to tell the server what data you want to send. Example:
Axios. Post ('/users', {id: "five fddfefc4fbd19494493cd71",name: "username"} // This part is the request body
).then(console.log)
Copy the code
- Axios is a library that sends requests. The browser also provides a function called fetch that can be used to send requests. There is also an outdated request library for sending requests.
- Post is the request method, indicating that we are sending information to the server. You can look at HTTP request methods in detail here.
- /users is the path that specifies the exact location in the server where you want to send the request. This PART of the URL is actually called the API. When an API follows a REST pattern, it becomes a REST API, allowing developers to quickly understand and use the API. For example, as the REST pattern says, paths should always be plural.
REST stands for declarative state passing, which is a set of design principles that allow you to use apis and modify resources on your server.
- The request body is the data object itself, so the server can retrieve the data.
As mentioned above, there are several ways to send a request to the server besides entering the domain name in the browser.
AJAX: Send requests from the browser. If someone says they know Ajax, that means they know how to send requests from the browser.
Cross-domain resource sharing
OPTIONS requests are also called pre-flight requests.
Currently, the response you see is coming from the Medium.com server. Suppose I write a JS code, and while you’re on the web browsing this, it’s sending a POST request to my own web server. This is called a cross-domain request.
Cross-domain Request: Send a URL request to a different host name from your current URL.
For example, I want to use JS code to send another request from the browser to another domain (another server), but you will find this is not easy. For security reasons, browsers restrict cross-source HTTP requests from scripts.
By default, the same-origin security policy forbids some cross-domain requests, especially Ajax requests, but always allows same-origin requests.
CORS defines how browsers and servers can interact and determines whether it is safe to allow cross-domain requests.
Cross-domain resource sharing (CORS) is a mechanism based on HTTP headers that allows the server to indicate any other source (domain, protocol, or port) that the browser should allow to load the resource.
Cross-domain request analysis
When the browser discovers that the domain is different, it sends an OPTIONS request to the server to check if the request is allowed. This behavior doesn’t really matter to us developers, because it’s something the browser does automatically. Developers can, however, add some headers to the request before sending it across domains, which may help get permission.
Just like any other browser request, some data in the table header provides some information. For example, the access-Control-request-method header sent through the OPTIONS Method provides information about when the actual Request is coming, what the data type is, what the Request Method is, and so on.
In this case, the server can respond to whether to accept the request, and the rest is up to the server. In response, the server can send back the access-Control-Allow-Origin header to indicate that the resource can be accessed by any domain.
While it allows GET requests from other domains, it may limit POST requests.
Cross-domain request response header
Access-control-allow-origin – Contains the host name that allows cross-domain requests to be sent. If this does not match the host name of the user’s site, the cross-domain request will be rejected.
Access-control-allow-credentials – If true in the response header, the cross-domain request contains Cookie headers.
Access-control-allow-methods – This is a comma-separated string that tells the browser which request Methods are allowed in cross-domain requests. If the request method is not included in this response header, the request will not be sent.
Set the header with node.js code:
router.options('/api/*'.(req, res) = > {
res.header('Access-Control-Allow-Credentials'.true)
res.header('Access-Control-Allow-Origin', req.headers.origin)
res.header('Access-Control-Allow-Methods'.'GET, PUT, POST, PATCH, DELETE')
res.header(
'Access-Control-Allow-Headers'.'Origin, X-Requested-With, Content-Type, Accept, Credentials'
)
res.send('ok')})Copy the code
conclusion
The CORS standard means that server developers must deal with new request and response headers. They need to use the header to draw the line so they can prevent security breaches.
In this article I have tried to introduce these important concepts in the most concise way possible, so please let me know if you have any questions or would like to learn more about one of the specific topics mentioned above.
Thanks for reading!
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.