As we know, we don’t have access to Django CSRFToken
in React by default, So we have to get it somehow.
The solution was make a URL for receive CSRFToken
in Response-Headers
and set csrftoken
cookie in browser. So I did it =>
Views.py
@method_decorator(ensure_csrf_cookie, name='dispatch')
class GetCSRFToken(APIView):
permission_classes = (permissions.AllowAny, )
def get(self, request, format=None):
return Response("CSRF cookie set.")
CSRFToken.jsx
import React, { useState, useEffect} from 'react';
import axios from 'axios';
export default function CSRFToken(){
useEffect(()=>{
const fetchData = async () => {
try {
const url = 'http://localhost:8000/csrf_cookie'
const response = await axios.get(url,{
withCredentials: true,
}).then(()=>{
console.log("CSRF Cookie set.")
})
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<>
</>
)
}
Result =>
After that we can access to csrftoken
and send it through X-CSRFToken
Request-Headers
.
But the problem is when I send the request Django side won’t accept that csrftoken
and will reject that request.
settings.py
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'App.apps.AppConfig'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = ['http://localhost:5173']
Views.py
@method_decorator(csrf_protect, name='dispatch')
class MarketDataView(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
...
FetchMarketData.js
export const fetchMarketData = createAsyncThunk(
'market/fetchData',
async ({requestData, csrftoken}, thunkApi) => {
try {
const url = 'http://localhost:8000/api/market'
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken
},
body: JSON.stringify({
exchange: 'binance'
}),
});
return await response.json();
} catch (error) {
return thunkApi.rejectWithValue(error);
}
}
);
Request Headers and Django Response =>
How can I solve this problem guys?