【问题标题】:CORS blocking post from jQuery来自 jQuery 的 CORS 阻止帖子
【发布时间】:2014-03-14 05:04:23
【问题描述】:

我正在尝试从一个伪装成远程 Web 服务器的静态页面发布到我的 Flask 应用程序中,由于 Flask-uWSGI-WebSocket 而在 uwsgi 后面运行。

每次我发帖到我的服务器时,帖子都会因为 CORS 被阻止: XMLHttpRequest cannot load http://127.0.0.1:5000/tnw/post. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我已经安装了 flask-cors 并且 origins 设置为 * 但我仍然无法通过它。我在这里还缺少什么?

我的帖子: $("#ajaxbutton").click(function() { var json = JSON.stringify(generate_json()); $.post('http://127.0.0.1:5000/tnw/post', json); });

【问题讨论】:

  • 您如何访问发出 CORS 请求的页面?是通过 http:// 还是 file:// (后者会给你一个'null'的起源,你不想要)。如果是后者,请尝试使用简单的 http 服务器(例如 python -m SimpleHTTPServer)。此外,您是否需要在此端点上进行任何类型的身份验证?如果是这样,并且它是基于 cookie 的,您需要将 withCredentials xhr 字段设置为 true 以允许 cookie 与请求一起发布 (docs)。
  • 把这个变成答案,这样我就可以接受了。
  • 出了什么问题?现在添加一个答案,但我想确保它为未来的读者解决了正确的问题。
  • 我通过 file:// 访问它

标签: jquery python flask cors uwsgi


【解决方案1】:

我认为这是两个问题之一:

  • 您正在访问通过file:// 协议而不是http:// 发出CORS 请求的页面。这会导致您拥有origin'null'。尝试通过http:// 访问它(例如python -m SimpleHTTPServer)。

  • 您的端点是否需要基于 cookie 的身份验证?默认情况下,jQuery 会忽略 CORS 请求中的 cookie。如果您需要随请求发送 cookie,请将 {xhrFields: withCredentials: true} 添加到您的 ajax 请求 (docs)。

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2020-07-08
    • 2019-05-21
    • 2020-11-04
    • 2019-07-28
    • 2020-08-29
    相关资源
    最近更新 更多