Birmingham-mumbai


Managing the CORS mechanism



tải về 6.62 Mb.
Chế độ xem pdf
trang267/275
Chuyển đổi dữ liệu09.10.2023
Kích6.62 Mb.
#55278
1   ...   263   264   265   266   267   268   269   270   ...   275
Sherwin John Tragura - Building Python Microservices with FastAPI Build secure, scalable, and structured Python microservices from design concepts to infrastructure-Packt Publishing - ebooks Account

Managing the CORS mechanism
When integrating API endpoints with various frontend frameworks, we often encounter the "no ‘access-
control-allow-origin’ header present" error from our browser. Nowadays, this setup is an HTTP-header-
based mechanism of any browser, which requires the backend server to provide the browser with the 
"origin" details of the server-side application, which includes the server domain, scheme, and port. 
This mechanism is called CORS, which happens when the frontend application and its web resources 
belong to a different domain area than the backend app. Nowadays, browsers prohibit cross-origin 
requests between the server-side and frontend applications for security reasons.


Utilizing Other Advanced Features
296
To resolve this issue, we need our 
main.py
module to place all the origins of our application 
and other integrated resources used by the prototype inside a 
List
. Then, we import the built-in 
CORSMiddleware
from the 
fastapi.middleware.cors
module and add that to the 
FastAPI
constructor with the list of origins, which should not be too long to avoid overhead from 
validating each URL. The following code snippet shows the injection of 
CORSMiddleware
into 
the 
FastAPI
constructor:
origins = [
"https://192.168.10.2",
"http://192.168.10.2",
"https://localhost:8080",
"http://localhost:8080"
]
app = FastAPI(middleware=[
Middleware(SessionMiddleware, 
secret_key
=
'7UzGQS7woBazLUtVQJG39ywOP7J7lkPkB0UmDhMgBR8=', 
session_cookie="session_vars"),
Middleware(SessionDbMiddleware, 
sess_key
=
'7UzGQS7woBazLUtVQJG39ywOP7J7lkPkB0UmDhMgBR8=',
sess_name='session_db', expiry='2020-10-10')
])

tải về 6.62 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   263   264   265   266   267   268   269   270   ...   275




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương