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

Axios将错误请求识别为CORS错误问题排查求助

解决方案

1. 修正Nginx配置,分离静态资源与API代理

删除Nginx中所有CORS相关add_header配置,同时调整路由,让React静态文件直接由Nginx返回,仅API请求代理到Django:

server {
    listen 80;
    server_name example.com;
    root /usr/share/nginx/html/build/;
    index index.html index.htm;

    # 处理React静态文件及单页路由
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 代理API请求到Django后端
    location /api/ {
        proxy_pass http://localhost:8000/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_redirect off;
    }
}

2. 统一用Django corsheaders处理CORS

在Django的settings.py中调整配置,确保符合CORS规范:

# 确认corsheaders已添加到INSTALLED_APPS和MIDDLEWARE
INSTALLED_APPS = [
    # ...其他应用
    'corsheaders',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # 必须放在CommonMiddleware之前
    'django.middleware.common.CommonMiddleware',
    # ...其他中间件
]

# 允许携带凭证(如cookie)
CORS_ALLOW_CREDENTIALS = True

# 指定允许的前端域名,禁止用*
CORS_ALLOWED_ORIGINS = [
    "http://example.com",  # 生产环境前端域名
    "http://localhost:3000",  # 开发环境本地地址
]

# 允许的请求头(按需调整)
CORS_ALLOW_HEADERS = [
    "accept",
    "authorization",
    "content-type",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]

3. 调整Axios配置,确保凭证传递

为Axios请求开启withCredentials,保证跨域请求时携带凭证:

const axiosPostRequest = ({url, useToken=true, data}) => {
  if (url && !url.startsWith('http')){
    url = HOST.toString() + url
  }
  let options = {
    withCredentials: true, // 新增:开启凭证传递
  }

  if (useToken) {
      options['headers'] = {}
      options['headers']['Authorization'] = `${AUTH_HEADER} ${getAuthToken()}`
  }
  
  return axios.post(url, data, options)
}

4. 验证错误响应头

用浏览器开发者工具查看错误请求的响应头,确认:

  • 不存在重复的CORS头
  • Access-Control-Allow-Origin为指定的前端域名,而非*
  • Access-Control-Allow-Credentials仅在需要时设置为true

内容的提问来源于stack exchange,提问作者mohamed naser

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:02:21