Struggling with CSRF token while making an axios post request to Django

Currently, I am facing an issue while using React + Django to make a post request via axios. The problem seems to be arising from csrf verification. Despite trying various solutions found online for similar issues, none of them seem to be effective in resolving the problem.

//Django View
def createUser(request):
    username = request.POST['username']
    email = request.POST['email']
    resp = {
      'username' : username,
      'email' : email
    }
    return JsonResponse(resp)



//Axios Post
axios.post('http://localhost:8000/api/createUser/',{
       username : 'xyz',
       email : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c2425261c3b31...[email protected]</a>'
    },
    {
       headers: {
         Content-Type': 'application/json',
       }
    });

I've attempted to resolve this by adding defaults:

axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";

However, the csrf validation continues to fail. Although I am aware that using @csrf_exempt on the view can bypass this issue, I would prefer to maintain the csrf check.

Answer №1

Make sure to add the cookies in the axios request along with the X-CSRFToken header by using withCredentials: true

Check out my initial response here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

Why is the Clean up function being utilized in this particular scenario in React?

What happens when I use the clean-up function compared to when I do not? It seems that both options result in the same outcome in terms of program execution, so why bother using the clean-up function at all? function MyComponent() { const [text, setTex ...

Launching a Material UI Modal nested within a parent component

I have a table displaying various teams. Each row in the table has a menu option that, when clicked, should open either a modal or a dialog box. I want to keep the table, menu functionality, and modals as separate components for better organization. Here&a ...

Ensure the function has completed setting state before proceeding to the next function

async componentDidMount() { this.loadSelectors(); this.useSelectors(); }; loadSelectors = () => { this.setState({"Selector": "Test"}); } useSelectors = () => { console.log(this.state.Selector); } Is there a way to ensure that loadS ...

Guide on embedding a form component within an iframe using ReactJS

I am trying to figure out how to render my form component inside an iframe, but so far it's only rendering the iframe itself. Any tips on how to accomplish this task? import './App.css'; import ReactDOM from "react-dom/client" impo ...

How can I configure the CSRF cookie name and header in Protractor to send a POST request to a Django server in order to set up a fixture for testing an Angular

I am facing a challenge with my Protractor test as I need to send a post request to a Django server to insert a fixture. In order to make this post request, I must adjust the xsrf setting within my app: app.config(['$httpProvider', function($htt ...

Leveraging webpack for loading images in a React application

I am encountering an issue with loading images after deploying to the server. I am unsure of the cause, but only a few images seem to render properly when using npm. Upon analysis: https://i.stack.imgur.com/ICgCN.png If the images load correctly with a ...

Setting up Swiper in a ReactJS environment

I've been trying to incorporate Swiper for a slider in my React application, but it's not behaving as expected. Here's what I did: npm install Swiper Then I imported Swiper in the componentDidMount method of my component like this: import ...

Struggling with running my React App as I'm encountering some errors

Check out the code on Github: https://github.com/bhatvikrant/IndecisionApp I have already run npm i and then executed yarn run dev-server, utilizing webpack. My operating system is MacOs. I have also created the .babelrc file. The issue I encountered aft ...

"Enhance your software with a customizable interface or develop new functionalities to generate analogous

Having API data with a similar structure, I am looking to streamline my code by filtering it through a function. However, as someone new to TypeScript, I am struggling to implement this correctly using a function and an interface. Essentially, I aim to ach ...

Subpar mobile performance on a React/Next.js website

Can someone assist me with improving my website's loading times? While the desktop version has a pagespeed ranking of 99, the mobile version only ranks 75. Click here to view the report on pagespeed.web.dev What steps can I take to improve this? I a ...

I'm having trouble pinpointing the cause of the never-ending loop in this React code that is using Material UI grid

There seems to be an issue with infinite looping in this code, and I can't figure out the cause, import React, { useEffect, useState } from 'react'; import VideoCardComponent from './VideoCard'; import Grid from '@mui/material ...

Testing the behavior of a Material UI Select component with React testing library's onChange event

Testing the onChange event for a Select component with react-testing-library is proving to be a challenge. After using getByTestId to grab the element successfully, setting the value and calling fireEvent.change(select);, the onChange does not trigger and ...

Encountering a problem with library functions while attempting to import a module

At the moment, I am utilizing NodeJS. I have been attempting to import a module into a component function and everything appears to be running smoothly. However, I keep encountering this error in the server console: error - src\modules\accountFu ...

Using React's useEffect and useContext can cause issues with certain components, particularly when dealing with dynamic routes

Currently, I am developing a React blog application where posts are stored in markdown files along with metadata in Firestore. The content .md files are saved in Cloud Storage. In the App component, I utilize useEffect to retrieve the metadata for each pos ...

Updating CSS for dropdown menu in Fluent/Fabric design

I am working with a dropdown component from Fluent UI and I am trying to customize the CSS of the dropdown options. Although I can add classes using className to the dropdown itself, I am facing difficulty in styling the dropdown options directly due to th ...

Utilize the Material UI SelectField component as a reference for handling onChange events

I'm facing a challenge with my form that contains over 15 SelectField components. I want to avoid creating multiple change handler functions, but I can't figure out how to identify the specific select field that triggered the change event in orde ...

Prevent modal from closing upon clicking a select option

After creating a customized filter for MUI's datagrid, I encountered an issue where the two select options in the filter were too large and ended up extending outside the modal. Whenever I clicked on an option, the entire modal would close unexpectedl ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...