【发布时间】:2021-04-09 19:20:04
【问题描述】:
我有两个烧瓶路由设置(使用 Flask Rest-X 定义),如下所示。
class Send(Resource):
def get(self: Any) -> Any:
session['foo'] = 'bar'
return {'message': session['foo']}
class Receive(Resource):
def get(self: Any) -> Any:
return {'message': session.get('foo', 'empty')}
两者都分别在 /send 和 /receive 注册为端点。这里没有什么聪明的地方,只有两个支持 GET 请求的烧瓶端点。
当我转到浏览器并转到 localhost:5000/send 时。 我应该返回 {'message': 'bar'} 。当我然后去 localhost:5000/receive 时,我得到了同样的结果。这意味着会话正在正常工作。
现在我有以下一段 javascript 尝试使用 fetch 做完全相同的事情。
fetch(`http://localhost:5000/send`, {
method: 'GET',
mode: 'cors',
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => {
fetch(`http://localhost:5000/receive`, {
method: 'GET',
mode: 'cors',
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => {setResponse(data)})
})
setResponse(data) 行类似于打印到控制台,它只是将输出写入屏幕,无论如何我都会返回 {'message': 'empty'} 所以使用 fetch 不能正确设置会话变量。
在我看来,这就像凭据和 CORS 的组合,但我似乎无法正确组合。
我试过了:
凭据:包含 -> 导致 CORS 错误。
凭证:同源 -> 空
凭证:同源和模式:cors -> 空
然后我尝试了一些新的东西。我像这样在 /receive 路由中添加了一个标题。
class Receive(Resource):
def get(self: Any) -> Any:
response = make_response({'message': session.get('me', 'empty')})
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
然后我尝试了凭据:再次包含.. 并且成功了!!我收到了 {'message': 'bar'}。所以它显然有效..但这是神秘的部分。我将 'foo' 和 'bar' 分别更改为 'one' 和 'two',然后再次尝试,现在我又回到了 {'message': 'empty'}。那么为什么当我添加响应标头时它突然对 foo/bar 起作用,为什么该响应标头不再起作用?是缓存问题吗?这个问题的组合让我有点发疯。
有人对如何让 fetch 与 Flask 会话一起工作有任何建议吗?
【问题讨论】: