Django CSRF Cookie+ReactJS Axios POST请求异常求助
Hey there, let's get your POST request working instead of just hanging at the OPTIONS pre-flight check. This is a super common issue with CORS and Django's CSRF protection, so let's break down what's going wrong and how to fix it step by step.
First, Understand the OPTIONS Request
That OPTIONS /endpointURL HTTP/1.1 200 response is the browser's pre-flight check—it's asking your server: "Hey, am I allowed to send a POST request with these headers and credentials?" If the server responds with the right CORS headers, the browser will fire the actual POST. If not, it stops here. Your issue is likely either a CORS configuration problem on the Django side, or conflicting CSRF settings in your Axios code.
Step 1: Fix Conflicting Axios CSRF Config
Looking at your code, you're setting global Axios CSRF defaults AND manually adding CSRF headers in your POST request—this is causing conflicts. The global Axios config already handles pulling the csrftoken cookie and setting the X-CSRFToken header automatically. Here's how to clean this up:
Updated Global Axios Config (../helpers/axios)
Keep this, but add withCredentials globally to avoid repeating it in every request:
import axios from 'axios' /** * Config global for axios/django */ axios.defaults.xsrfHeaderName = "X-CSRFToken" axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.withCredentials = true // Add this to send credentials automatically axios.defaults.baseURL = "http://endpointurl" // Optional: Set base URL to shorten requests export default axios
Simplified POST Request Code
Remove the manual CSRF headers—Axios will handle them for you:
import axios from '../helpers/axios'; axios({ method: "post", url: "/your-specific-endpoint", // Use relative path if you set baseURL above data: { name: this.state.name, } }) .then(res => { console.log(res); console.log(res.data); }) .catch(err => { console.error('Request failed:', err.response?.data || err.message); // Add catch to debug errors })
Step 2: Clean Up Token Handling
Your current code stores csrftoken and XSRF-TOKEN in localStorage, but this is unnecessary. Axios's global config already pulls the csrftoken directly from the cookie—no need to copy it to localStorage. You can delete that entire getCookie/localStorage block unless you need those tokens for something else unrelated to Axios requests.
Step 3: Fix Django CORS & CSRF Settings
The most likely reason the browser isn't firing the POST after OPTIONS is missing or incorrect CORS headers from Django. Here's how to configure it properly using django-cors-headers:
1. Install the package
pip install django-cors-headers
2. Update settings.py
Add these configurations to ensure your frontend is allowed to send authenticated requests:
# Add corsheaders to INSTALLED_APPS INSTALLED_APPS = [ ... 'corsheaders', ... ] # Add CorsMiddleware BEFORE CommonMiddleware in MIDDLEWARE MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] # Allow your frontend origin (replace with your actual frontend URL) CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", # Add other allowed origins if needed ] # Allow credentials (required because you're using withCredentials: true) CORS_ALLOW_CREDENTIALS = True # Trust your frontend origin for CSRF (critical for Django's CSRF protection) CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000", ]
Step 4: Debug with Browser Dev Tools
To confirm everything is working:
- Open your browser's DevTools (F12) and go to the Network tab.
- Trigger your POST request.
- Check the OPTIONS request's Response Headers:
- Ensure
Access-Control-Allow-Originmatches your frontend URL. - Ensure
Access-Control-Allow-Credentials: trueis present. - Ensure
Access-Control-Allow-MethodsincludesPOST.
- Ensure
If these headers are missing, double-check your Django CORS settings. If they're present but the POST still doesn't fire, check the Console tab for any JavaScript errors.
内容的提问来源于stack exchange,提问作者dorina

