OxygenFramework / Oxygen.jl

💨 A breath of fresh air for programming web apps in Julia
https://oxygenframework.github.io/Oxygen.jl/
MIT License
383 stars 25 forks source link

CORS Support - Follow Up #149

Closed uvrey closed 5 months ago

uvrey commented 5 months ago

Hello!

Thanks for your work on this project; it's been really helpful so far. I would like to configure CORS so I can serve an API. I've followed the examples in demo/main.jl as well as another issue, using the following code:

headers = [
    "Access-Control-Allow-Origin" => "*",
    "Access-Control-Allow-Headers" => "*",
    "Access-Control-Allow-Methods" => "GET, POST"
]

function CorsHandler(handle)
    return function (req::HTTP.Request)
        # return headers on OPTIONS request
        if HTTP.method(req) == "OPTIONS"
            return HTTP.Response(200, headers)
        else
            r = handle(req)
            append!(r.headers, ["Access-Control-Allow-Origin" => "*"])
            r

        end
    end
end

# more code here
serve(middleware=[CorsHandler])
end

However, I'm getting this error: got unsupported keyword argument "middleware"

Do you know if CORS is integrated yet / if so, how best to configure it in the current Oxygen.jl version?

Thank you!

ndortega commented 5 months ago

Below is a full working example of Cors in oxygen. Cors isn't natively supported by oxygen, but it can be enabled through middleware functions. I've also moved the headers outside the middleware so we only have to compute these once and can just return them inside the middleware.

module CorsDemo

using HTTP
using Oxygen

allowed_origins = [ "Access-Control-Allow-Origin" => "*" ]

cors_headers = [
    allowed_origins...,
    "Access-Control-Allow-Headers" => "*",
    "Access-Control-Allow-Methods" => "GET, POST"
]

function CorsHandler(handle)
    return function (req::HTTP.Request)
        # return headers on OPTIONS request
        if HTTP.method(req) == "OPTIONS"
            return HTTP.Response(200, cors_headers)
        else
            r = handle(req)
            append!(r.headers, allowed_origins)
            return r
        end
    end
end

get("/") do
   text("hello world")
end

# more code here
serve(middleware=[CorsHandler])

end

To test this, go to google.com, open up the browser console, and paste & run this code to hit the server:

fetch("http://127.0.0.1:8080/").then(r => r.text()).then(console.log)

You can validate things are working by adding & removing the CorsHandler from the global middleware keyword and check if you get a successful response back from the server.

ndortega commented 5 months ago

I've added this file to the demo directory for future use by others. If you encounter any other problem, feel free to start a discussion or raise another issue