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

通过JS发送fetch请求时间歇性出现403错误

间歇性POST请求返回403(Django + Fetch API)

我用JavaScript的fetch + await调用Django开发的POST API,请求间歇性返回201或403状态码——10次调用里大概7次会出现403错误。

代码片段:

const apiCalls = number_arr.map(async (event) => {
    const response = await fetch(`{% url 'base_check_url' %}?number=${event.attrs.value}`, {
        method: "POST",
        credentials: 'include',
        headers: {'Content-Type': 'text/plain'},
    });
});

错误响应截图:
错误响应截图


排查与解决方向

  • CSRF令牌问题(最可能)
    Django默认启用CSRF保护,POST请求必须携带有效CSRF令牌。批量并发请求时,易出现令牌重复使用或请求间令牌更新导致失效的情况:

    1. 确保每次请求获取最新CSRF令牌,添加到请求头:
      // 从Cookie获取CSRF令牌
      function getCookie(name) {
          let cookieValue = null;
          if (document.cookie && document.cookie !== '') {
              const cookies = document.cookie.split(';');
              for (let i = 0; i < cookies.length; i++) {
                  const cookie = cookies[i].trim();
                  if (cookie.substring(0, name.length + 1) === (name + '=')) {
                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                      break;
                  }
              }
          }
          return cookieValue;
      }
      
      // 发起请求时携带CSRF头
      const csrftoken = getCookie('csrftoken');
      const response = await fetch(`{% url 'base_check_url' %}?number=${event.attrs.value}`, {
          method: "POST",
          credentials: 'include',
          headers: {
              'Content-Type': 'text/plain',
              'X-CSRFToken': csrftoken
          },
      });
      
    2. 避免并发复用令牌:将批量请求改为串行执行,确保每次请求使用的令牌有效。
  • 请求并发与Session冲突
    Django默认基于Cookie管理Session,并发请求可能导致Session状态不一致,引发未授权判定。改为串行执行请求:

    async function processNumbers() {
        for (const event of number_arr) {
            const csrftoken = getCookie('csrftoken');
            const response = await fetch(`{% url 'base_check_url' %}?number=${event.attrs.value}`, {
                method: "POST",
                credentials: 'include',
                headers: {
                    'Content-Type': 'text/plain',
                    'X-CSRFToken': csrftoken
                },
            });
            // 处理响应逻辑
        }
    }
    processNumbers();
    
  • Content-Type与请求体适配
    当前请求设置Content-Type: text/plain,若后端未明确处理该类型,可尝试移除该Header,或确认视图是否能正确解析text/plain格式的请求。同时检查URL参数number是否存在格式异常。

  • Django后端配置排查
    检查CSRFViewMiddleware是否正常启用,查看API视图的权限装饰器(如@login_required)是否存在逻辑漏洞。可查看Django的django.request日志,获取403错误的具体触发原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:37:52