How to handle cross origin?

Why do we do that?

Browser will poke cross site server with OPTIONS method to determine the access right.

  • If browser don't see the right header, then it won't take the data.

  • If server side don't handle OPTIONS method correctly, a server side exception may be raised.

REST

  • To handle corss site origin request and response, implement middleware corsapp.middleware.CorsMiddleware

    class CorsMiddleware(object):
    
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            response = self.get_response(request)
            response["Access-Control-Allow-Origin"] = "*"
            response["Access-Control-Allow-Headers"] = "*"
            response["Access-Control-Allow-Methods"] = "*"
    
            return response

    And adjust settings in bookstore_openapi.settings.py

      MIDDLEWARE = [
          ...
          'corsapp.middleware.CorsMiddleware',
      ]
  • To bypass cross origin, 3 access control attributes were added to response.

GraphQL

  • To handle corss site origin request and response, implement middleware corsapp.middleware.CorsMiddleware

    And adjust settings in bookstore_graphql.settings.py

  • To bypass cross origin, 3 access control attributes were added to response.

gRPC

Last updated

Was this helpful?