socketify.py
socketify.py copied to clipboard
How to enable CORS?
Hi, May I know how to enable CORS in Socketify?
I am trying to add any CORS using middleware but it seems doesn't work at all.
async def cors_middleware(req, res):
res.set_header("Access-Control-Allow-Origin", "*")
res.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
res.set_header("Access-Control-Allow-Headers", "Content-Type")
auth_router = MiddlewareRouter(app, cors_middleware)
I think returning False/None (this function returns None implicitly) stops execution, so you may wish to return True at the bottom
https://docs.socketify.dev/middlewares.html
You can just send the headers like:
from socketify import App
import asyncio
app = App()
router = app.router()
def cors(*headers):
return headers + (
("Access-Control-Allow-Origin", "*"),
("Access-Control-Allow-Headers", "*"),
("Access-Control-Allow-Methods", "*"),
("Access-Control-Allow-Credentials", "true"),
("Access-Control-Max-Age", "86400"),
)
def allow_cors(res, req, data=None):
res.send(None, headers=cors((b'Content-Length', b'0')))
app.options("*", allow_cors)
@router.get("/")
def home(res, req, data=None):
res.send({"Hello": "World!"}, headers=cors((b'Another-Headers', b'Value')))
app.listen(
3000,
lambda config: print("Listening on port http://localhost:%d now\n" % config.port),
)
app.run()