What steps do I need to follow to send a POST request using JavaScript in Django while including the CSRF token?

I've encountered a similar issue where the solutions provided didn't quite work for me:

Fetch, set-cookies and csrf

Proper Django CSRF validation using fetch post request

Even though I believe my post request content is correct, I still keep getting a 403 error.

        const url = "/post/create"
        let csrftoken = Cookies.get('csrftoken'); //using library


        const headers = new Headers({
                'X-CSRF-TOKEN': csrftoken
            });
            return fetch(url, {
                method: 'POST',
                headers,
                credentials: 'same-origin',
                mode: 'same-origin',
                body: JSON.stringify({
                    content: content
                })
            });

Any thoughts on what might be causing this?

UPDATE: Here's the solution I managed to come up with

        fetch(url, {
            method: 'POST',
            mode: "same-origin",
            headers: {
                "X-CSRFToken": csrftoken,
                "Accept": "network/json",
                "Content-Type": "network/json",
            },
            body: JSON.stringify({
                content: content
            })

Answer №1

Remember to use X-CSRFToken instead of X-CSRF-TOKEN. Check out additional information 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

The absence of the pyramid in the WEB GL canvas is noticeable

I encountered an issue while attempting to generate two shapes on the canvas: an octagon and a pyramid. The octagon displays correctly, but the pyramid does not appear as expected. Below is the code snippet related to the creation of the pyramid: pyramidP ...

Pausing until the user clicks the button again

I have implemented two buttons on this page - one with a class of 'arrow-up' and the other with a class of 'arrow-down'. Clicking on the 'arrow-down' button will smoothly scroll down to the next section, while clicking on the ...

The error "Uncaught TypeError: Cannot read property 'render' of undefined" occurs when using Three.js along with OrbitControls

I am having an issue with my rotating cube class. Whenever I try to rotate or zoom the cube, I encounter an error message saying "Cannot read property 'render' of undefined". I suspect that the problem lies within the scopes. Below is my class im ...

Archive a webpage with refreshed content using ajax

Is there a way to save a webpage that has been updated through an ajax request? I'm looking to preserve basecamp message threads, but exporting is not possible since I am not the account owner. When attempting to use the javascript command below: jav ...

Troubles with adding a semicolon when configuring cookies in Javascript with Angular

While attempting to implement cookies with TypeScript in Angular, I ran into an unexpected issue. My intention was to save some data in a cookie for future testing purposes. The line of code that caused the problem was: document.cookie = "token=" + value ...

Is there a way for me to customize the appearance of the Material UI switch component when it is in the checked

I am seeking to customize the color of the switch component based on its checked and unchecked state. By default, it displays in red. My goal is to have the "ball knob" appear yellow when the switch is checked and grey when it is not. This styling must be ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

How come CSS styles are not being applied to forms in AngularJS?

When attempting to apply CSS styles to a form in order to indicate invalid input, I encountered an issue. Even after using the important tag, the styles did not change. I created a dynamic form from JSON and now need to validate it. Following a suggestion ...

What is the best way to process the bytes from xhr.responseText?

Is there a way to successfully download a large 400+ mb Json file using xmlhttprequest without encountering the dreaded Ah Snap message in Chrome due to its immense size? One potential solution I've considered is implementing setInterval() to read th ...

Vue modifies the array in the data after creating a duplicate of it

Here is the Vue code snippet I'm working with: export default { name: 'Test', data() { return { test1: ['1', '2', '3'], test2: [{ name: 'Hello' }, { name: &apo ...

The process of transferring a file from a client to a server and then from one server to another

Within my web application, I am currently working on implementing a file upload feature. I have successfully utilized axios to send file requests from the client to the server's API, including proper form data appending and necessary headers. However, ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...

An express error caught off guard: Unexpected "write after end" issue detected

My current goal is to create a proxy for an api call from the client side through my server for a third party service. The main reasons for implementing this proxy are due to CORS issues and the need to include a secret key on the server side for added sec ...

derive values from radio group inputs

Attempting to compute a selection value based on a radio group and values from additional fields. Any input in the 'Name' field contributes a value to the Total. The value from the radio group needs to be added to this total. Below is the HTML co ...

What is the best way to eliminate all click event handlers with jQuery?

I'm encountering an issue where multiple click events are being attached to a button. Specifically, when a user clicks on an 'Edit' link, the following JQuery code is executed: $("#saveBtn").click(function () { saveQuestion(id); }); Ea ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

Submitting JSON with Nested Relationships in Django REST Framework: A Step-by-Step Guide

Currently utilizing Django version 2.1 and DRF 3.7.7. In my setup, I have multiple nested models along with their corresponding serializers which are also nested. Here's a simplified example to illustrate: # db_models.py class Country(models.Model) ...

Concealing a hyperlink depending on the value chosen in a dropdown menu

Looking for guidance on how to use jQuery to read the current value of a drop-down list and hide a specific link based on that value. The drop-down list is for selecting the language/locale. For example, when "English" is selected, I want the link to be h ...