如何在 julia Genie 应用程序中设置 cors 标头以允许来自不同域的 POST 请求

kim*_*kim 5 julia

我在开发应用程序时使用精灵后端和反应前端,但是,每当我尝试从反应应用程序将数据发布到后端时,我都会收到错误

Access to XMLHttpRequest at 'http://127.0.0.1:8000/simplex' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value ''.
xhr.js:155 POST http://127.0.0.1:8000/simplex net::ERR_FAILED
Run Code Online (Sandbox Code Playgroud)

但是使用 julia Http post 发布数据它按预期工作,我知道这是我的服务器中的 cors 标头的问题,但我只进入 Genie 两天,我可以找到一种方法来做到这一点,我尝试添加我的配置但从来没有帮助反正

const config = Settings(
    server_port                     = 8000,
    server_host                     = "0.0.0.0",
    log_level                       = Logging.Debug,
    log_to_file                     = false,
    server_handle_static_files      = true,
    websocket_server                = false,
   cors_allowed_origins             = ["*"] #tried adding this
)
Run Code Online (Sandbox Code Playgroud)

小智 5

经过几个小时的挫折后,我发现这会起作用。我正在从 Angular 连接到 Genie。看起来您需要指定所有这些才能使其工作。一定是出了什么问题。

纳特拉吉

在routes.jl文件中:

using Genie, Genie.Router, Genie.Requests, Genie.Renderer.Json
using HTTP

using SolutionsController
Genie.config.run_as_server = true
Genie.config.cors_headers["Access-Control-Allow-Origin"] = "http://localhost:4200"
# This has to be this way - you should not include ".../*"
Genie.config.cors_headers["Access-Control-Allow-Headers"] = "Content-Type"
Genie.config.cors_headers["Access-Control-Allow-Methods"] ="GET,POST,PUT,DELETE,OPTIONS" 
Genie.config.cors_allowed_origins = ["*"]
# This is also needed 

Genie.Router.route("/api/json", SolutionsController.API.myOMJason, method="POST")


Run Code Online (Sandbox Code Playgroud)