【发布时间】:2017-03-19 21:47:46
【问题描述】:
我有一个 django 后端,并且我启用了跨源请求,如下所示:
INSTALLED_APPS = [
..
'corsheaders',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
我还没有实施任何身份验证。我只是想访问一个 API 端点并尝试在我的 Angular2 前端获取数据。
我在 Django 后端实现了一个基于会话的购物车,用于存储我的产品 (https://github.com/lazybird/django-carton)。当我通过可浏览的 api 点击http://127.0.0.1:8000/api/shopping-cart/show/ 时,它给了我
{"1":{"product_pk":1,"price":"23000.00000","quantity":3},"2":{"product_pk":2,"price":"34000.00000","quantity":7},"4":{"product_pk":4,"price":"450.00000","quantity":1}}
但是,当我尝试从我的 Angular2 服务中访问相同的网址时:它会抛出错误:
XMLHttpRequest cannot load http://127.0.0.1:8000/api/shopping-cart/show/. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
我的服务调用如下:
private myUrl: string = 'http://127.0.0.1:8000/api/shopping-cart/'
showCart(){
return this.http.get(this.myUrl + 'show' + '/', {withCredentials:true})
.toPromise()
.then(response => response.json())
}
注意:如果我删除 {withCredentials:true} 那么它不会发送 sessionid 或 csrftoken 并返回 {} 但错误消失了。我做错了什么?
【问题讨论】: