Python 当从另一个服务器进程访问Django API时,如何避免跨源资源共享错误?
我正在构建一个WebApp,它有两个独立的组件:Python 当从另一个服务器进程访问Django API时,如何避免跨源资源共享错误?,python,django,node.js,cors,django-cors-headers,Python,Django,Node.js,Cors,Django Cors Headers,我正在构建一个WebApp,它有两个独立的组件: web访问者将访问的“frontend”node.js应用程序服务器(运行在localhost:3099上) 一个“后端”Django服务器(运行在localhost:3098上),用于管理我的ORM并与数据库通信。Web访问者根本不会与此服务器直接交互。此服务器只发布前端将使用的RESTful API 我将实施安全限制,以防止除前端服务器之外的任何人访问后端的API 后端发布的一个API端点如下所示:http://localhost:3098/
http://localhost:3098/api/myApi/
我可以通过curl成功地访问该API,如下所示:curl-xpost-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'
添加到我的已安装的应用程序中
'django.middleware.common.CommonMiddleware'上面的中间件类中添加了'corsheaders.middleware.corsmidleware'
CORS\u ORIGIN\u白名单=('localhost','127.0.0.1',)
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三元组,则当且仅当它们具有相同的方案、主机和端口时,这两个源是相同的
这意味着,对于您的spec,CORS将您的白名单处理为localhost:80127.0.0.1:80
。我认为指定localhost:3099
应该可以解决这个问题