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

Django-React项目POST请求静默失败,无Django报错仅Axios返回ECONNABORTED

Django-React项目POST请求ECONNABORTED错误排查

问题背景

Django-React项目中,某POST API调用失败,DEBUG模式下Django控制台无任何错误信息,仅Firefox控制台捕获到Axios的ECONNABORTED(请求中止)错误。

相关代码

Django后端

views.py
class OrdersList(generics.ListCreateAPIView):
    queryset = models.Order.objects.all()
    serializer_class = serializers.OrderSerializer
urls.py
path('orders/', views.OrdersList.as_view()),

React前端请求代码

const formData = new FormData();
formData.append('customer_id', customerId);
axios.post(createOrderUrlRef.current, formData).then((response) => {
     console.log(`${TAG} ${JSON.stringify(response)}`);
}).catch((error) => {
     console.log(`${TAG} error: ${JSON.stringify(error)}`);
});

错误信息

OrderConfirmation error: {"message":"Request aborted","name":"AxiosError","stack":"AxiosError@http://localhost:3000/static/js/bundle.js:88555:18\nhandleAbort@http://localhost:3000/static/js/bundle.js:87934:14\...","headers":{"Accept":"application/json, text/plain, */*"},"method":"post","url":"http://127.0.0.1:8000/api/orders/","data":{}},"code":"ECONNABORTED","status":null}

排查方向及解决办法

  • 检查跨域配置:Django默认禁止跨域,前端localhost:3000和后端127.0.0.1:8000属于不同域名,需配置django-cors-headers:

    1. 安装依赖:pip install django-cors-headers
    2. 在settings.py中添加配置:
      INSTALLED_APPS = [
          # 其他应用
          'corsheaders',
      ]
      
      MIDDLEWARE = [
          'corsheaders.middleware.CorsMiddleware',
          'django.middleware.common.CommonMiddleware',
          # 其他中间件
      ]
      
      CORS_ALLOWED_ORIGINS = [
          "http://localhost:3000",
          "http://127.0.0.1:3000",
      ]
      
  • 调整请求超时:Axios默认超时时间较短,后端处理慢会触发中止,可手动设置超时:

    axios.post(createOrderUrlRef.current, formData, { timeout: 10000 }) // 设置10秒超时
    .then(response => console.log(`${TAG} ${JSON.stringify(response)}`))
    .catch(error => console.log(`${TAG} error: ${JSON.stringify(error)}`));
    
  • 验证请求数据与后端接收:

    1. 确认OrderSerializer中customer_id字段类型匹配(如IntegerField)且必填
    2. 在Django视图中添加日志,确认请求是否到达后端:
      import logging
      
      logger = logging.getLogger(__name__)
      
      class OrdersList(generics.ListCreateAPIView):
          queryset = models.Order.objects.all()
          serializer_class = serializers.OrderSerializer
      
          def post(self, request, *args, **kwargs):
              logger.info(f"Received request data: {request.data}")
              return super().post(request, *args, **kwargs)
      
      查看Django控制台日志,判断请求是否进入视图。
  • 检查后端服务与端口:

    1. 确认Django服务正常运行在127.0.0.1:8000,浏览器直接访问http://127.0.0.1:8000/api/orders/验证响应
    2. 检查防火墙或代理是否拦截端口,确保3000和8000端口开放
  • 核对请求URL:确认createOrderUrlRef.current的值为http://127.0.0.1:8000/api/orders/,无拼写错误(如缺少api前缀)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 03:23:19