我在Django
后端公开了API。我想从Angular 7
获取该API请求。所以我实现了
this.HttpClient.get('Http://127.0.0.1:8000/myapp/posts')
.subscribe(
(data:any[]) => {
console.log(data)
}
)
但是我收到一个错误
Access to XMLHttpRequest at 'http://127.0.0.1:8000/myapp/posts' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}message: "Http failure response for (unknown url): 0 Unknown Error"name: "HttpErrorResponse"ok: falsestatus: 0statusText: "Unknown Error"url: null__proto__: HttpResponseBase
有人可以建议解决此错误的任何方法吗?
答案 0 :(得分:1)
当使用浏览器的访存API,Axios客户端或jQuery $ .ajax()方法(JavaScript XHR接口的包装器)从前端应用程序发送HTTP请求到使用以下命令构建的后端API时Django REST框架的Web浏览器将引发与Same Origin Policy相关的错误。
跨源资源共享或CORS通过使现代Web浏览器能够绕过默认实施的同源策略来允许客户端应用程序与不同域上托管的API交互。
在此处引用操作方法:https://www.techiediaries.com/django-cors/
您需要添加一个中间件文件app / cors.py:
class CorsMiddleware(object):
def process_response(self, req, resp):
response["Access-Control-Allow-Origin"] = "*"
return response
这将向每个Django请求添加一个Access-Control-Allow-Origin:*标头,但在此之前,您需要将其添加到中间件类列表中:
MIDDLEWARE_CLASSES = (
#...
'app.CorsMiddleware'
)
然后安装django-cors-headers
首先使用pip安装django-cors-headers
pip install django-cors-headers