How can I setup cors headers in julia Genie app to allow POST request from different domain

Viewed 493

I am using genie backend and react frontend in development of my application, however, whenever I try to post data to the backend from my react app I get error

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

but posting data using the julia Http post it works as expected, I know this is an issue with cors headers in my server but am only two days into Genie and I can find a way to do it, i tried adding my config but never helped anyway

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
)
2 Answers

After hours of frustration, I figured out that this will work. I am connecting from Angular to Genie. It looks like you need to specify all these for it to work. Must be some glitch.

Natraj

In the routes.jl file:

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")


FYI you can also fix this in your config/env files like this:

using Genie.Configuration, Logging

const config = Settings(
  server_port                     = 8005,
  server_host                     = "0.0.0.0",
  log_level                       = Logging.Debug,
  log_to_file                     = true,
  server_handle_static_files      = true,
  cors_headers                    = Dict(
                                      "Access-Control-Allow-Origin" => "YOUR_ORIGIN",
                                      "Access-Control-Allow-Headers" => "Content-Type",
                                      "Access-Control-Allow-Methods" => "GET,POST")
)

You can also set YOUR_ORIGIN to * if you want

Related