Closed uvrey closed 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.
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
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: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!