Django + Django Rest Framework 实践

Django CORS Problem

2019-04-17  本文已影响0人  思考的虫子

Python: 3.5
Django: 2.1.5

Problem Desc:
Django works as an API backend, frontend use VUE.
The request was blocked by CORS policy because the header doesn't involve 'Access-Control-Allow-Origin'.

15554720745855.png
  1. install django-cors-headers
pipenv install django-cors-headers
  1. add to settings.py
INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)
  1. add middleware to settings.py
MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]
  1. add your request source to whitelist
# replace with your own frontend server address
CORS_ORIGIN_WHITELIST = (
    '<server address>'
)
  1. restart service, done!
上一篇下一篇

猜你喜欢

热点阅读