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

首次使用Django框架:AJAX携带API Token调用第三方Django API持续返回401 Unauthorized错误求助

Troubleshooting Django API 401 Unauthorized with AJAX

Hey there, let's work through this 401 error together—since you're new to Django, I'll break down the most likely issues and fixes in plain, actionable terms:

1. You're missing the API Token in your request headers

The biggest red flag here is that you mentioned you have an API Token, but your AJAX code isn't sending it to the server. Most Django-based APIs (especially those using Django REST Framework) expect API Tokens to be sent in an Authorization header using this exact format:

Authorization: Token YOUR_API_TOKEN_HERE

Your current code only includes the CSRF token, which is needed for Django's form protection but doesn't handle API authentication. That's almost certainly why you're getting the 401.

2. Stop hardcoding your CSRF token!

You've hardcoded the CSRF token as "XXXXXXXXXXXXXXX"—this is risky because CSRF tokens expire and are unique per user session. Instead, grab it directly from the browser's cookies (Django sets this cookie automatically for you):

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();
            // Check if this cookie matches the CSRF token name
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

3. Updated AJAX code with both required headers

Here's how your code should look with the API Token added and proper CSRF token retrieval:

const csrftoken = getCookie('csrftoken');
const apiToken = "YOUR_REAL_API_TOKEN"; // Replace with your actual token

$.ajax({ 
  type: 'POST', 
  headers: { 
    'X-CSRFTOKEN': csrftoken, 
    'Authorization': `Token ${apiToken}`,
    'Content-Type': 'application/json' 
  }, 
  url: 'www.service-provider.url/api/...', 
  success: function (response) { 
    console.log("Success! Data:", response); 
  }, 
  error: function (xhr) { 
    console.log("Error status:", xhr.status);
    console.log("Error details:", xhr.responseText); // This will give you specific Django error messages!
  } 
});

4. Extra checks to rule out other issues

  • Confirm your API Token is valid: Double-check with your service provider that the token is active, hasn't expired, and has permission to access the specific endpoint you're calling.
  • Verify the request method: Make sure the API endpoint accepts POST requests—some read-only endpoints require GET instead.
  • Check for CORS issues: If your frontend is hosted on a different domain than the API, ask your provider if they've configured CORS to allow your domain and custom headers like Authorization.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:57:34