- 1. 引言
- 2. 跨源資源共享和實(shí)現(xiàn)方法
-
3. 在Django項(xiàng)目中配置django-cors-headers庫(kù)
- Reference
1. 引言
在進(jìn)行后端API開發(fā)時(shí),有時(shí)會(huì)遇到“跨域資源共享 (CORS) 請(qǐng)求...被阻止“的錯(cuò)誤,如圖1所示。本文講解如何在使用DRF(Django REST Framework)的后端API開發(fā)項(xiàng)目中解決這個(gè)問題。
A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated?preflight request?.
...
2. 跨源資源共享和實(shí)現(xiàn)方法
跨源資源共享(Cross-Origin Resource Sharing)是一種機(jī)制,允許在Web瀏覽器的安全性限制下,從一個(gè)域(網(wǎng)站)的客戶端向另一個(gè)域的服務(wù)器發(fā)送跨域HTTP請(qǐng)求。
DRF官方給出有關(guān)跨域資源共享的兩種實(shí)現(xiàn)方式:
(1)在 REST 框架中處理 CORS 的最佳方法是在中間件中添加所需的響應(yīng)標(biāo)頭,這種方式透明地支持 CORS,無需更改視圖中的任何行為。
(2)使用django-cors-headers。
Cross-Origin Resource Sharing?is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
Adam Johnson?maintains the?django-cors-headers?package, which is known to work correctly with REST framework APIs.
3. 在Django項(xiàng)目中配置django-cors-headers庫(kù)
(1)使用pip在環(huán)境中安裝django-cors-headers
庫(kù):
python -m pip install django-cors-headers
(2)在setting.py
文件的INSTALLED_APPS
中添加"corsheaders"
:
INSTALLED_APPS = [
...,
"corsheaders",
...,
]
(3)在setting.py
文件的MIDDLEWARE
中添加中間件類用于監(jiān)聽響應(yīng):
MIDDLEWARE = [
...,
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
...,
]
(4)在setting.py
文件中添加變量CORS_ALLOWED_ORIGINS
并設(shè)置為True
.
CORS_ALLOWED_ORIGINS = True
以上步驟完成后,前端調(diào)用后端DRF API時(shí)所出現(xiàn)的CORS錯(cuò)誤就被消除了。文章來源:http://www.zghlxwxcb.cn/news/detail-857592.html
Reference
AJAX, CSRF & CORS - Django REST framework
GitHub - adamchainz/django-cors-headers: Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)文章來源地址http://www.zghlxwxcb.cn/news/detail-857592.html
到了這里,關(guān)于前端調(diào)用DRI后端API出現(xiàn)跨域資源共享(CORS)問題解決辦法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!