【问题标题】:How to set cookie from Flask web server如何从 Flask Web 服务器设置 cookie
【发布时间】:2019-05-23 21:39:35
【问题描述】:

我有一个问题,我创建了一个托管在 Heroku 上的 Flask Web 服务器,其中包含一个在 Chrome 中存储 cookie 的功能。

cookie的存储函数如下:

@app.route('/api/v1.0/setcookie', methods=['GET'])
def setcookie():
    series = str(np.random.randint(10**8, 10**9))
    token = str(np.random.randint(10**8, 10**9)).encode('utf-8')
    hashed_token = hashlib.sha256(token).hexdigest()
    resp = make_response()
    resp.set_cookie('huga_series_id', series, max_age=60*60*24*365*5)
    resp.set_cookie('huga_series_token', token, max_age=60*60*24*365*5)
    cookies = mongo.db.cookies
    cookies.insert({'series': series, 
        'token': hashed_token})
    return resp

此函数是 Flask Web 服务器的一部分,托管在 URL https://my-server-name.herokuapp.com/

问题是:当我访问 URL https://my-server-name.herokuapp.com/api/v1.0/setcookie 时,cookie 已正确存储在我的 Chrome 浏览器中。但是,如果我尝试使用 XMLHTTTPREQUEST 从 Javascript 向该 URL 提交 GET 请求,如下所示:

    var xxhttp = new XMLHttpRequest();
    xxhttp.open("GET", "https://my-server-name.herokuapp.com//api/v1.0/setcookie", true);
    xxhttp.send();

不存储任何 cookie。我已经完成了测试,我相信一切——XMLHttpRequest 发送、Python 代码等都能正常工作。这两种方法的唯一区别是我在一个中通过 Javascript 提交 GET 请求,在另一个中手动访问 URL。

关于如何使用 XMLHttpRequest 在 Chrome 中存储 cookie 有什么想法吗?

谢谢!

【问题讨论】:

    标签: javascript google-chrome cookies flask xmlhttprequest


    【解决方案1】:

    首先,尝试改用Fetch API。如果您还必须支持旧浏览器,请使用this poly-fill。您的 XMLHttpRequest 问题可能与设置 cookie 时未设置路径有关(关于其工作原理有一些意想不到的规则)。与其尝试使用旧 API 修复它,不如使用更好的 Fetch API 并阅读此about setting cookies

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      相关资源
      最近更新 更多