How can I enable CORS on my Django REST Framework? the reference doesn't help much, it says that I can do by a middleware, but how can I do that?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
and then add it to your installed apps:
You will also need to add a middleware class to listen in on responses:
more details: https://github.com/ottoyiu/django-cors-headers/#configuration
read the official documentation can resolve almost all problem
Well, I don't know guys but:
using here python 3.6 and django 2.2
Renaming MIDDLEWARE_CLASSES to MIDDLEWARE in settings.py worked.
For Django versions > 1.10, according to the documentation, a custom MIDDLEWARE can be written as a function, let's say in the file:
yourproject/middleware.py
(as a sibling ofsettings.py
):and finally, add the python path of this function (w.r.t. the root of your project) to the MIDDLEWARE list in your project's
settings.py
:Easy peasy!
You can do by using a custom middleware, even though knowing that the best option is using the tested approach of the package
django-cors-headers
. With that said, here is the solution:create the following structure and files:
--
myapp/middleware/__init__.py
--
myapp/middleware/corsMiddleware.py
add to
settings.py
the marked line:The link you referenced in your question recommends using
django-cors-headers
, whose documentation says to install the libraryand then add it to your installed apps:
You will also need to add a middleware class to listen in on responses:
You might also want to browse the configuration section of its documentation, paying particular attention to the various
CORS_ORIGIN_
settings.In case anyone is getting back to this question and deciding to write their own middleware, this is a code sample for Django's new style middleware -