我正在开发我的第一个Web应用程序,前端使用React
,后端使用FastAPI
。
我试图与Chrome一起测试它 - 查看前端是否正确地调用了后端的API,并显示结果。我一直在遇到有关cookies的问题,希望得到帮助。事先对这篇长文章道歉-过去几天我已经查阅了许多资源,现在我不确定哪些是相关的,哪些不是。
- 前端位于
localhost:8080
- 后端位于
http://127.0.0.1:8000
- 以下为
FastAPI
后端代码中CORS的正确设置(我认为):
app = FastAPI()
origins = [
"http://localhost:8080"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
情况: 前端向后端发出 GET
请求 http://127.0.0.1:8000/api/abc
,后端设置了一个 cookie。
/*====================
尝试 1:
使用以下后端代码设置 cookie:
response.set_cookie(key="abcCookieKey", value="abcCookieValue")
使用以下前端JS代码进行GET
请求:
fetch('http://127.0.0.1:8000/api/abc', {
method: 'GET',
credentials: 'include',
})
第一次尝试的结果:
在Chrome的控制台
选项卡中,我收到以下警告:
A cookie associated with a cross-site resource at http://127.0.0.1/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
在网络选项卡上,当我检查set-cookie
响应头时,会得到以下消息:
This Set-Cookie was blocked because it has the "SameSite=Lax" attribute but came from a cross-site response which was not the response to a top-level navigation.
====================*/
...所以我进行了一些研究,并想出了
/*====================
尝试2:
使用以下后端代码设置cookie:
response.set_cookie(key="abcCookieKey", value="abcCookieValue", samesite="none", secure=True)
使用相同的前端JS代码进行GET
请求。
第二次尝试的结果:
在Chrome的Console
选项卡中,我收到了与第一次尝试相同的警告,即使响应标头具有set-cookie
和Samesite = none; Secure
。此外,标头还具有以下警告
This Set-Cookie was blocked because it had the "Secure" attribute but was not received over a secure connection.
====================*/
..所以我尝试使用 https
并得到:
/*====================
尝试 3:
除了在我的 JS fetch 代码中,我使用 fetch('https://127.0.0.1:8000/api/abc ...
,其他和尝试 #2 相同,
然后我在运行 uvicorn
的后端收到以下警告: WARNING: Invalid HTTP request received.
====================*/
问题:
- 我在尝试 #2 中有遗漏吗?肯定有一种简单的方法可以从后端向前端设置 cookie 而不必担心 https 吧?
- 如果我别无选择只能使用
https
,如何本地运行可以通过https
访问的后端服务器?我所做的研究似乎表明这是一个复杂 / 费时的过程。(但公平地说,我对 Web 开发 / 所有网络相关的事情的理解非常有限)。