如何在从另一个服务器进程访问Django API时避免跨域资源共享错误?
我正在构建一个网页应用,它有两个独立的部分:
- 一个“前端”node.js应用服务器(运行在localhost:3099),这是网页访问者会访问的地方。
- 一个“后端”Django服务器(运行在localhost:3098),它负责管理我的数据库操作,并与数据库进行沟通。网页访问者不会直接与这个服务器互动。这个服务器只是发布一个RESTful API,前端会使用这个API。
我会设置一些安全限制,确保只有前端服务器可以访问后端的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.
为了解决这个问题,我采取了以下步骤:
- 我安装了 django-cors-headers
- 我在我的
INSTALLED_APPS
中添加了'corsheaders'
- 我在
MIDDLEWARE_CLASSES
中添加了'corsheaders.middleware.CorsMiddleware'
,并放在'django.middleware.common.CommonMiddleware'
之前。 - 我声明了白名单:
CORS_ORIGIN_WHITELIST = ('localhost', '127.0.0.1',)
然而,实施django-cors-headers似乎没有任何效果。我仍然遇到相同的CORS错误。我该如何解决这个问题?
1 个回答
1
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.
而且
如果两个来源的协议、主机和端口都相同,那么这两个来源就是相同的,只有在它们的协议、主机和端口完全一致时,才算是相同。
这就是说,根据你的规范,CORS会把你的白名单视为 localhost:80, 127.0.0.1:80
。我认为指定 localhost:3099
应该能解决这个问题。