烧瓶会话不持久(邮递员工作,Javascript不工作) [英] Flask Session Not Persisting (Postman works, Javascript doesn't)

查看:98
本文介绍了烧瓶会话不持久(邮递员工作,Javascript不工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Flask服务器,以通过Web在某些后端Python功能和Javascript客户端之间进行通信.我试图利用Flask的session变量在与应用程序交互的过程中存储用户特定的数据.我在下面删除了大多数应用程序特定的代码,但我遇到的核心问题仍然存在.

I'm developing a Flask server to communicate between some backend Python functionality and Javascript clients over the web. I'm attempting to utilize Flask's session variable to store user specific data over the course of their time interacting with the app. I've removed most of the application specific code below but the core problem I'm experiencing remains.

这是我(简化的)Flask应用程序的代码:

Here is my the code for my (simplified) Flask app:

import json
import os
from flask import Flask, jsonify, request, session

app = Flask(__name__)
app.secret_key = 'my_secret_key'

@app.route('/', methods=['GET'])
def run():
  session['hello'] = 'world'
  return jsonify(session['hello'])

@app.route('/update', methods=['POST'])
def update():
  return jsonify(session['hello'])

if __name__ == '__main__':
  app.run(host='0.0.0.0')

使用邮递员,我可以向服务器发出GET请求,并接收"world"的预期输出.然后,我可以使用任意主体发出POST请求,并接收与"world"相同的预期输出(再次使用Postman).

Utilizing Postman, I can make a GET request to my server and receive the expected output of "world". I can then make a POST request with an arbitrary body and receive the same expected output of "world" (again using Postman).

使用Chrome时,我可以访问服务器IP并在页面上看到预期的输出"world".我还可以使用Javascript(在Chrome的控制台中)手动发出GET请求,并收到与预期相同的响应.但是,尝试使用Javascript向服务器发送POST请求时出现了我的问题.尝试发出此请求时,服务器显示KeyError: 'hello'.

When using Chrome, I can visit my server IP and see the expected output "world" on the page. I can also manually make a GET request using Javascript (in Chrome's console) and receive the same response as expected. However, my problem arises when trying to send a POST request to the server using Javascript; the server shows a KeyError: 'hello' when trying to make this request.

这是我用来发出POST请求的Javascript:

Here is the Javascript I'm using to make the POST request:

var url = 'http://my_server_ip/update';
fetch(url, {
  method: 'POST',
  body: JSON.stringify('arbitrary_string'),
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
.then(response => response.json())
.then((data) => {
  console.log(data);
})

这是怎么回事?为什么我可以使Postman的GET/POST请求很好,但是使用Javascript进行相同的请求时却出错了?

What's going wrong here? Why can I make the GET/POST requests with Postman just fine but run into errors making the same requests with Javascript?

推荐答案

经过几个小时的测试,我设法弄清了这个问题.尽管我认为@amanb的答案突出了问题所在,但我将回答自己的问题,因为我发现最终是一个更简单的解决方案.

After a few hours of testing, I managed to figure out the issue. Although I think @amanb's answer highlights the problem, I'm going to answer my own question because what I found is ultimately a simpler solution.

为了使POST请求返回期望值,我只需要在fetch正文中添加credentials: 'same-origin'行.如下所示:

In order to make the POST request return the expected value, I simply needed to add a credentials: 'same-origin' line to the fetch body. This looks like the following:

var url = 'http://my_server_ip/update';
fetch(url, {
  method: 'POST',
  body: JSON.stringify('arbitrary_string'),
  credentials: 'same-origin',   // this line has been added
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then((data) => {
  console.log(data);
})

根据 Mozilla的Fetch使用指南

默认情况下,抓取不会从服务器发送或接收任何Cookie, 如果站点依赖于,则会导致未经身份验证的请求 维护用户会话.

By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session.

所以看来我已经看过了.更改凭据以允许客户端和服务器之间的cookie/会话通信可以解决该问题.

So it seems I looked over this. Changing the credentials to allow communication of the cookie/session between client and server resolved the issue.

这篇关于烧瓶会话不持久(邮递员工作,Javascript不工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆