使用 falcon 网络服务器在本地主机上违反了同源策略

Same Origin Policy violated on localhost with falcon webserver

我是 运行 一个榆树前端,通过 elm-reactor 在 localhost:8000 上。它应该通过 localhost:8010 上的 gunicorn 从 falcon 后端 运行 加载 json 文件。这失败了。

前端能够加载由 elm-reactor (:8000) 提供的静态虚拟文件,但是当我尝试用实际后端 (:8010) 替换虚拟文件时,它失败了缺少 header:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8010/api/sheets. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Firefox Inspector 的错误消息似乎相当清楚,但我不知道如何解决它。我已经在 falcon 中安装了 CORS 中间件,但这根本没有改善这种情况。

from falcon_cors import CORS
cors = CORS(allow_origins_list=['*'])
api = falcon.API(middleware=[cors.middleware])

我也曾尝试使用起源 'localhost:8000''localhost' 但都不起作用。

知道如何解决这个问题吗?

原来falcon_cors提供了allow_all_origins=True作为参数。这解决了我的问题,但不是完美的解决方案。

同时使用 POST 请求时 allow_all_methods=True 也应设置。

试试这个。希望这能解决您的问题。

import falcon
from falcon_cors import CORS
cors = CORS(allow_origins_list=['http://localhost:8080', 'http://localhost:8000', 'http://localhost:8010'], allow_all_headers=True, allow_methods_list=['GET', 'POST', 'OPTIONS'])
api = falcon.API(middleware=[cors.middleware])