【发布时间】:2019-10-11 10:29:33
【问题描述】:
我有一个在 Django Rest Framework 中开发的 API,它在我的浏览器和邮递员中调用时可以工作,但在 Angular 中调用时会给出“(失败)”响应。不提供响应代码(例如 404)
在控制台日志中,它声称由于 CORS,但同一浏览器允许它然后直接调用。
获取:
Access to XMLHttpRequest at 'http://localhost:8000/article/articletype' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
我从 Django 控制台知道调用成功,因为它给出了 200 响应。
我尝试通过向 Angular 调用添加标头来允许 CORS 从两端绕过。以下是我允许的访问控制。 我也玩过不同的 Content-Types 和 Accepts(是 text/html),但现在列为 *
'Accept' : '*/*' , 'Content-Type': '*' , 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers':'*'
对于 Django,我添加了带有 CORS_ORIGIN_ALLOW_ALL = True 的“corsheaders”插件
我也尝试过在 Django 中返回 JSON 和 JsonResponse 的 HttpResponse。
在 Django RFW 中:
目前代码看起来像这样,但我尝试了很多不同的迭代
jresponse = {
"id" : 2,
"text" : response,
"prev_button" : "...prev",
"subject1" : "SomeSub",
"stage" : "SomeStage",
"type1" : "SomeType1",
"type2" : "SomeType2",
"subject_list" : ["Sub1","Sub2","Sub3","Sub4"],
"stage_list" : ["Stage1","Stage2","Stage3","Stage4"],
"type1_list" : ["Type1.1","Type1.2", "Type1.3","Type1.4"],
"type2_list" : ["Type2.1","Type2.2","Type2.3","Type2.4"],
}
jr=json.dumps(jresponse)
jr['Access-Control-Allow-Origin'] = '*'
jr['Access-Control-Allow-Headers'] = '*'
# jr = serialize('json', response) # Tried this, didn't work
# return JsonResponse(jresponse) # Tried this, didn't work
return HttpResponse(jresponse) # I have also tried returning the 'jr' variable
在我所有的迭代中,我通常会在浏览器中得到响应。
对于 Angular:
getArticles() {
let add = 'http://localhost:8000/page/'.concat(this.articleid);
this.http.get(add,
{headers : { 'Accept' : '*/*' , 'Content-Type': '*' , 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers':'*' }}
).subscribe(
article => { this.article = article;
console.log(this.article)
})
如前所述,Accept 和 Content-Type 已经通过工厂。
我希望 Angular 接收我可以在模板中使用的 Json 对象
例如:{{article.subject}}
【问题讨论】:
-
您是否正确配置了CORS中间件? (在普通中间件之前)
-
GET 请求不执行飞行前 CORS 检查。您问题中的错误是针对“localhost:8000/article/articletype”,但您的代码未访问该 URL
标签: django angular django-rest-framework cors