cirospaciari / socketify.py

Bringing Http/Https and WebSockets High Performance servers for PyPy3 and Python3
https://www.socketify.dev
MIT License
1.34k stars 47 forks source link

How to enable CORS? #171

Closed perogeremmer closed 1 week ago

perogeremmer commented 3 months ago

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)
leunga1000 commented 2 months ago

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

cirospaciari commented 1 week ago

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