In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what are the CORS implementation models?". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
CORS implements two models
1.1
Simple model
Get/post/put/delete requests are supported, for example, Access-Control-Allow-Origin:*, is returned but custom header is not allowed and cookies is ignored. Post data format is limited. Only 'text/plain',' application/x-www-urlencoded'and'multipart/form-data', where 'text/plain'' is supported by default. The latter two require the following pre-check request and server negotiation.
1.2
Negotiation model / pre-inspection request (Preflighted Request)
For example: the browser issues a PUT request, and the OPTION request returns Access-Control-Allow-Origin: allows the browser's script to execute the data returned by the server.
The cross-domain resource sharing standard adds a set of HTTP header fields that allow the server to declare which origin server has access to which resources through the browser. In addition, the specification requires that for HTTP request methods that may have side effects on server data (especially HTTP requests other than GET, or POST requests with some MIME types), browsers must first use the OPTIONS method to initiate a pre-check request (preflight request) to know whether the server allows the cross-domain request. The server confirms the permission before initiating the actual HTTP request. In the return of the pre-check request, the server can also inform the client whether it needs to carry identity credentials (including Cookies and HTTP authentication-related data).
two
FastAPI uses CORSMiddleware middleware to implement CORS.
2.1
Use CORSMiddleware
We use CORSMiddleware in FastAPI applications through the following process
1. Import CORSMiddleware
2. Create a list of allowed origins
3. Introduce CORSMiddleware middleware into the application.
4. Authentication information (Authorization headers, Cookies, etc.)
5. Supported HTTP methods (POST,GET, or all ")
From fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddleware
App = FastAPI ()
Origins = ["http://127.0.0.1"," https://www.baidu.com", "https://www.hao123.com"," http://localhost:8080",]
App.add_middleware (CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods= ["*"], allow_headers= ["*"],)
App.get ("/") async def main (): return {"message": "Hello World,"}
2.2
CORSMiddleware parsing
The default values of parameters in CORSMiddleware are restricted, and in order to support the corresponding functions in cross-domain access, we should display information specifying specific parameters. The information of CORSMiddleware supporting parameters is as follows:
1. Allow_origins: list of domain names that allow cross-domain requests, such as ['https://example.org', 'https://www.example.org']' or [']
2. Allow_origin_regex: domain name regular expressions that allow cross-domain requests, such as' https://..example.org'
3. Allow_methods: list of HTTP methods that allow cross-domain requests. Default is ['GET'], and ['] means all HTTP methods are allowed.
4. Allow_headers: list of HTTP header information supported for cross-domain requests. ['] indicates that all header information is allowed. Accept, Accept-Language, Content-Language and Content-Type header information are all supported by default
5. Allow_credentials: indicates whether cookie is supported for cross-domain requests. Default is False.
6. Expose_headers: indicates the returned result header information visible to the browser. Default is []
7. Max_age: the maximum time for the browser to cache CORS to return the result. Default is 600 (in seconds).
three
Type of request
Browsers divide CORS requests into two categories: simple requests (Simple requests) and non-simple requests, also known as pre-check requests (CORS preflight requests).
3.1
Definition of simple request and non-simple request
It is a simple request as long as the following two conditions are met at the same time.
1. The request method is one of the following three methods: HEAD, GET, POST
The header information of 2.HTTP does not exceed the following fields: Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type: limited to three values: application/x-www-form-urlencoded, multipart/form-data and text/plain. If the above two conditions are not met at the same time, it is a non-simple request.
3.2
The difference between the two requests handled by the browsing area
1. Simple request for simple request, the browser sends out CORS request directly. Specifically, add an Origin field to the header information. The Origin field is used to indicate which source this request comes from (protocol + domain name + port). Based on this value, the server decides whether to agree to the request or not. In this case, the middleware will pass the request information normally, but the appropriate CORS header information will be included in the return result.
2. A pre-check request is a non-simple request that has special requirements on the server, such as the request method is PUT or DELETE, or the type of Content-Type field is application/json.
For CORS requests that are not simple requests, an HTTP query request, called a "pre-check" request (preflight), is added before formal communication.
The browser first asks the server whether the domain name of the current web page is on the server's license list, and which HTTP methods and header information fields can be used. Only when you get an affirmative answer will the browser issue a formal request, otherwise it will report an error.
The request method used for the "pre-check" request is OPTIONS, indicating that the request is used to ask. In the header information, the key field is Origin, indicating which source the request comes from.
In addition to the Origin field, the header information of the pre-check request includes two special fields.
1.Access-Control-Request-Method this field is required to list which HTTP methods will be used in the browser's CORS request. The above example is PUT.
2.Access-Control-Request-Headers this field is a comma-separated string that specifies the additional header information field that the browser CORS request will send. The example above is X-Custom-Header. After receiving the "pre-check" request, the server can respond after checking the Origin, Access-Control-Request-Method, and Access-Control-Request-Headers fields to confirm whether cross-source requests are allowed.
In this case, the middleware intercepts the request information and returns different request result information depending on whether cross-domain requests are allowed.
four
Comparison with JSONP
CORS is used for the same purpose as JSONP, but is more powerful than JSONP. JSONP supports only GET requests, and CORS supports all types of HTTP requests. JSONP has the advantage of supporting older browsers and the ability to request data from websites that do not support CORS.
five
CORS Summary:
1. Give the definition of CORS.
two。 How to use CORSMiddleware Middleware to realize CORS in fastapi
3. The comparison between CORS and JSONP is given.
This is the end of the content of "what is the CORS implementation model?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.