【发布时间】:2020-11-10 14:23:07
【问题描述】:
我目前正在开发我的第一个 web 应用程序,前端使用 React,后端使用 FastAPI。
我正在尝试与 Chrome 一起测试它——看看前端是否对后端进行了正确的 API 调用,并显示结果。我一直在使用 cookie 时遇到问题,我需要帮助。提前为这篇长文道歉——过去几天我浏览了很多资源,现在我不确定什么是相关的,什么不是。
-
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=["*"],
)
情况:前端向后端的http://127.0.0.1:8000/api/abc发出GET请求,后端设置了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',
})
尝试 1 的结果:
在 Chrome 的 Console 标签上,我收到以下警告:
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 请求。
尝试 2 的结果:
在 Chrome 的 Console 选项卡上,我收到与尝试 1 完全相同的警告,即使响应标头具有 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:
一切都与尝试 #2 相同,除了在我的 JS 获取代码中,我使用 fetch('https://127.0.0.1:8000/api/abc ...
然后我在使用uvicorn 运行的后端收到以下警告:WARNING: Invalid HTTP request received.
====================*/
问题:
- 尝试#2 是否遗漏了什么?肯定有一种简单的方法来设置从后端到前端的 cookie,而不用担心 https?
- 如果我别无选择,只能使用
https,如何在本地运行可以使用https访问的后端服务器?我所做的研究使它看起来像是一个复杂/耗时的过程。 (但是,公平地说,我对 web-dev/all things network 的理解非常有限)。
【问题讨论】:
-
你解决了吗?
-
简短的回答是否定的,我没有解决它。我刚结束使用 Safari 来解决它,然后在部署后检查它是否可以在 Chrome 上运行。
-
你是怎么解决沙山的?
-
请发布答案@ShashanSooriyahetti,因为您可以看到我们很多人都想知道。
-
@Marisha 我已经添加了答案,因为你们要求随时问 anthing
标签: reactjs google-chrome cookies fastapi samesite