[英]Cross-Origin Resource sharing error: Header Disallowed by preflight response
[英]How to avoid Cross-Origin Resource Sharing error when hitting a Django API from another server process?
我正在構建一個具有兩個獨立組件的WebApp:
我將實施安全限制,以防止除前端服務器之外的任何人訪問后端的API。
后端發布的API端點之一如下所示: http://localhost:3098/api/myApi/
。
我可以從curl像這樣成功地擊中該API: curl -X POST -H "Content-Type: application/json" -d '{"myKey1":"myVal1", "myKey2":"myVal2"}' http://localhost:3098/api/myApi/
但是,當我嘗試使用Javascript從前端服務器訪問相同的API時,在瀏覽器的控制台窗口中出現以下錯誤:
XMLHttpRequest cannot load http://localhost:3098/api/myApi/.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3099' is therefore not allowed access.
要解決此問題,請執行以下步驟:
'corsheaders'
我INSTALLED_APPS
'django.middleware.common.CommonMiddleware'
上方'django.middleware.common.CommonMiddleware'
MIDDLEWARE_CLASSES
添加了'corsheaders.middleware.CorsMiddleware'
'django.middleware.common.CommonMiddleware'
CORS_ORIGIN_WHITELIST = ('localhost', '127.0.0.1',)
但是,實現django-cors-header似乎沒有什么區別。 我仍然遇到相同的CORS錯誤。 我該如何解決這個問題?
CORS具有端口敏感性。 規格說明
If there is no port component of the URI:
1. Let uri-port be the default port for the protocol given by uri-scheme.
Otherwise:
2. Let uri-port be the port component of the URI.
和
如果兩個來源是scheme / host / port三元組,則僅當兩個來源具有相同的方案,主機和端口時,兩個來源相同。
這意味着,按照您的規范,CORS會將白名單處理為localhost:80, 127.0.0.1:80
。 我相信指定localhost:3099
應該可以解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.