socketify.py icon indicating copy to clipboard operation
socketify.py copied to clipboard

How to enable CORS?

Open perogeremmer opened this issue 1 year ago • 1 comments

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)

perogeremmer avatar Apr 15 '24 09:04 perogeremmer

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

leunga1000 avatar May 02 '24 18:05 leunga1000

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()
Screenshot 2024-07-13 at 12 17 06

cirospaciari avatar Jul 13 '24 19:07 cirospaciari