我一直在寻找这个问题的解决方案,但似乎没有什么工作。我已经到达了django-cors-headers包,但不能让它工作。
我正在从我的vue
前端发送一个axios
请求:
axios.get('data/')
.then(res => { console.log(res) })
但是它抛出了一个200 network error
错误:
Access to XMLHttpRequest at 'http://localhost:8000/data/' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
GET http://localhost:8000/data/ net::ERR_FAILED 200
AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_NETWORK"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Network Error"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …}
stack
:
"AxiosError: Network Error\n
Django后端
我正在重定向**myProject/urls.py
**中的传入请求:
from django.urls import path, include
urlpatterns = [
path('', include('myApp.urls')),
]
至**myApp/urls.py
**:
from django.urls import path
from . import views
urlpatterns = [
path('data/', views.getData)
]
调用**myApp/views.py
**:
from rest_framework.response import Response
from rest_framework.decorators import api_view
from base.models import Item
from .serializers import ItemSerializer
@api_view(['GET'])
def getData(request):
items = Item.objects.all()
serializer = ItemSerializer(items, many=True)
return Response(serializer.data)
带有**base/models.py
**:
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
和**myApp/serializers.py
**:
from rest_framework import serializers
from base.models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
我已经安装了django-cors-headers
软件包,并在**myProject/settings.py
**中进行了配置:
INSTALLED_APPS = [
'corsheaders',
...
]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
]
其中一项为:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
或
CORS_ALLOW_ALL_ORIGINS = True
但是两个都不起作用。我试着阅读package docs,但是找不到错误。
1条答案
按热度按时间tnkciper1#
它抛出200网络错误错误
根本就没有“200网络错误”这回事:如果你得到一个200的状态码,那就说明网络没有问题,因为浏览器确实收到了服务器的响应。2相反,由于某种原因,CORS检查失败了;因此,浏览器拒绝您的客户端访问响应并引发CORS错误。
CORS策略已阻止从源“http://localhost:3000”访问位于“http://localhost:8000/data/”的XMLHttpRequest:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能为通配符“*”。XMLHttpRequest启动的请求的凭据模式由withCredentials属性控制。
如果您收到这样的错误消息,那是因为
您的问题没有显示出来,但我怀疑您已将Axios客户端配置为始终发送带有凭据的请求。但是,在CORS配置中设置
CORS_ALLOW_ALL_ORIGINS
而不同时设置CORS_ALLOW_CREDENTIALS
会导致以下响应标头,而通配符恰好与认证请求不兼容。如果要允许认证请求,还需要在CORS配置中设置以下内容:
否则,请指示Axios客户端不要发送认证请求。