我有一个Django的后端和我已经启用跨源请求如下:angular2:起源的“http://本地主机:3000”因此不允许访问
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)基于会话的购物车。当我打http://127.0.0.1:8000/api/shopping-cart/show/通过我可浏览API它给我
{"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:真正}然后它不会发送会话ID或csrftoken并返回{}但误差消失。我究竟做错了什么?如果你使用withCredentials: true
好了,在哪里以及怎样在我的要求加上这个? – Nitish
没有什么可以做的请求。浏览器在来自服务器的响应中预期在resposne头文件中。我不知道Django以及如何配置它。 –