You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Axios对接Django REST Framework时CSRF Token缺失引发403错误的代码配置方案

Fixing CSRF Token Issue with Axios and Django REST Framework

Got it, let's resolve that 403 CSRF error properly instead of disabling CSRF protection (which is a big no-no for production). Here's exactly how to add the required CSRF token to your React + Axios code:

First, confirm Axios is imported

Double-check that the top of your component file includes this import (you're already using Axios, so this is likely there, but it's good to verify):

import axios from 'axios';

Step 1: Add a helper to extract the CSRF token from cookies

Django automatically sets a csrftoken cookie when you visit your site. We need to pull that value out to send with our POST request. Add this function in your component file:

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;
}

Step 2: Configure Axios to use the CSRF token (two options)

You can either set this globally (so all Axios requests use the token) or add it manually to individual POST requests. The global approach is cleaner:

Option 1: Global Axios Configuration (Recommended)

Add this in your component's constructor to apply the token to every request automatically:

constructor(){
  super()
  this.state = {
    persons: []
  }

  // Tell Axios to grab the CSRF token from the cookie and send it in the correct header
  axios.defaults.xsrfCookieName = 'csrftoken';
  axios.defaults.xsrfHeaderName = 'X-CSRFToken';
}

Option 2: Manual Header for Individual POST Requests

If you prefer to only add the token to specific requests, modify your post method like this:

post(){
  const csrfToken = getCookie('csrftoken');
  axios.post('http://127.0.0.1:8000/api/create', {
    title: 'titan',
    body: 'this is working',
  }, {
    headers: {
      'X-CSRFToken': csrfToken
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(error => console.error('POST Error:', error)) // Add catch to debug issues
}

Full Modified Component Code

Here's your complete component with all fixes (including global config and error handling, plus a component name change to avoid conflicts with the Axios library):

import React from 'react';
import axios from 'axios';

// Helper to extract CSRF token from browser cookies
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;
}

class AxiosComponent extends React.Component{
  constructor(){
    super()
    this.state = {
      persons: []
    }

    // Global Axios CSRF configuration
    axios.defaults.xsrfCookieName = 'csrftoken';
    axios.defaults.xsrfHeaderName = 'X-CSRFToken';
  }

  post(){
    axios.post('http://127.0.0.1:8000/api/create', {
      title: 'titan',
      body: 'this is working',
    })
    .then(response => console.log(response))
    .catch(error => console.error('POST Request Error:', error))
  }

  get(){
    axios.get('http://127.0.0.1:8000/api')
    .then(response => console.log(response.data))
    .catch(error => console.error('GET Request Error:', error))
  }

  componentDidMount(){
    this.post();
    this.get();
  }

  render(){
    return(
      <div>
        <h1>Axios Requests</h1>
      </div>
    )
  }
}

export default AxiosComponent;

Quick Notes

  • Cookie Existence: Make sure you've loaded your Django site in the browser before running the React app—otherwise the csrftoken cookie won't exist yet.
  • CORS Setup: If your React app runs on a different port (like 3000) than Django (8000), install django-cors-headers and set CORS_ALLOW_CREDENTIALS = True in your Django settings.py to allow cookies to be sent across origins.

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

火山引擎 最新活动