所以问题出在localhost
。
我有一个在localhost:5000上运行的Flask后端和一个在localhost:3000上运行的React SPA。
背景和问题
我有一个在localhost:5000上运行的Flask后端和一个在localhost:3000上运行的React SPA。我能够使他们交谈,但是当尝试将Flask生成的令牌存储到浏览器的Cookie中时:1)从console.log(response)
成功执行POST后执行axios
时,响应标头不包含任何cookie,以及2)不会组。但是当检查网络> Login.js标头时,我实际上可以看到Set-Cookie
键作为响应的标头存在。我已经尝试过Google和StackOverflow的多种解决方案,但似乎没有解决方案在这里起作用,而且我真的不知道发生了什么,因为成功完成了请求,Chrome允许第三方软件设置Cookie。甚至我也可以从Network> Login.js标头中看到令牌。
步骤
1)用户输入用户名和密码并点击登录。
2)对Flask的后端进行Axios POST调用。
3)处理数据并生成几个令牌并将它们设置为cookie。
4)浏览器的cookie设置的令牌很少。
代码
使用flask-jwt-extended
]的Flask后端令牌生成># app_config related to flask-jwt-extended
CORS_HEADERS = "Content-Type"
JWT_TOKEN_LOCATION = ["cookies"]
JWT_COOKIE_SECURE = False
JWT_COOKIE_CSRF_PROTECT = True
# post method from flask-restful for LoginAPI class
def post(self):
email = request.json.get("email")
password = request.json.get("password")
# some processing here.....
payload = {
"email": email
}
access_token = create_access_token(identity=payload)
refresh_token = create_refresh_token(identity=payload)
response = jsonify({"status": True})
set_access_cookies(response, access_token)
set_refresh_cookies(response, refresh_token)
return response
CORS使用flask-cors
我不确定这是否正常,但响应的标头未显示我从后端设置的任何Cookie。# in below code, I had some issues with putting wildcard (*) into origin, so I've specified to the React SPA's host and port. CORS(authentication_blueprint, resources={r"/authentication/*": {"origins": "http://localhost:3000"}}, supports_credentials=True)
React SPA-使用
axios
]进行发布通话># also tried `axios.defaults.withCredentials = true;` but same result. export const login = (email, password, cookies) => { return dispatch => { const authData = { email: email, password: password }; let url = 'http://127.0.0.1:5000/authentication/login/'; axios.post(url, authData, {withCredentials: true) .then( response => { console.log(response) }) .catch(err => { console.log(err) }); dispatch(authSuccess(email, password)); } };
下图是
axios
中成功邮寄的响应。
下面的图片来自网络>登录头标题/
如图所示,您可以通过Set-Cookie
键清楚地看到令牌信息。我还检查了它们是否不是secure
。
最后,当我从应用程序中检查我的cookie选项卡> cookie时,我什么也看不到。
背景和问题我有一个运行于localhost:5000的Flask后端,以及一个运行于localhost:3000的React SPA。我能够使他们交谈,但是当尝试存储从Flask生成的令牌时...
所以问题出在localhost
。
我有一个在localhost:5000上运行的Flask后端和一个在localhost:3000上运行的React SPA。
根据上面的陈述,非常明确地说,我在localhost:5000上运行后端,而在127.0.0.1:3000上运行React SPA。
一旦将127.0.0.1
更改为localhost
,它就像一个超级按钮。
还有一个旁注,在使用CORS
之后,我认为使用Nginx
和proxy_pass
将来自React SPA的请求传递到后端要容易得多,避免使用CORS
完全,因为如果必须在不同的环境(例如测试,暂存等)中使用CORS
,则无论如何都必须在Web服务器级别设置CORS
,例如Nginx
,并且它需要稍有不同的配置无论如何我要如何设置本地环境。
所以问题出在localhost
。
我有一个在localhost:5000上运行的Flask后端和一个在localhost:3000上运行的React SPA。