You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django后端配置django-cors-headers后,Axios GET请求仍遇CORS问题如何解决?

Django + Vue CORS 跨域问题排查与解决

问题现象

从Vue前端通过Axios发送请求:

axios.get('data/')
    .then(res => { console.log(res) })

返回200状态码但触发网络错误,核心报错信息:

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__'

已尝试的CORS配置

已安装django-cors-headers包,在myProject/settings.py中配置:

INSTALLED_APPS = [
    'corsheaders',
    ...
]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
]

先后尝试两种配置均无效:

  1. 指定允许源:
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]
  1. 允许所有源:
CORS_ALLOW_ALL_ORIGINS = True

解决方案

1. 适配凭证携带的CORS配置

报错核心原因:请求开启了withCredentials: true(凭证模式为include),此时后端不能用*作为允许源,需补充配置:

  • 保留CORS_ALLOWED_ORIGINS指定前端地址,同时添加:
CORS_ALLOW_CREDENTIALS = True
  • 确保CORS_ALLOW_ALL_ORIGINS设为False,避免配置冲突

2. 调整Axios请求的凭证设置

如果业务不需要携带Cookie、HTTP认证信息等凭证,可直接关闭withCredentials:

// 单请求配置
axios.get('data/', { withCredentials: false })
    .then(res => { console.log(res) })

// 全局配置
axios.defaults.withCredentials = false;

3. 修正中间件顺序

CorsMiddleware必须放在尽可能靠前的位置,尤其是在CommonMiddleware之前:

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...  # 其他中间件
]

4. 验证响应头

通过浏览器开发者工具的Network标签,确认响应头包含:

  • Access-Control-Allow-Origin: http://localhost:3000(而非*)
  • 开启凭证时需存在Access-Control-Allow-Credentials: true

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:40:34