Struggling to send a POST request using the Fetch API? The provided examples may not be effective

I am encountering an issue with sending a post request to the server. The request.POST on the server seems to be empty for some unknown reason. Below are examples of the code:

Front-end JavaScript:

let weekends = []
    await fetch('{% url "get_weekends" %}', {
        method: 'POST', headers: new Headers({'Accept': 'application/json', 'Content-Type': 'application/json'}),
        params: {after: after_str, before: before_str}
    }).then(function (response) {
        return response.json();
    }).then(function (data) {
        if (data['status'] === 'ok') {
            weekends = data['weekends']
        } else {
            console.error(data)
            show_error('Failed to retrieve your weekends list! Error in status!')
        }
    }).catch(function (e) {
        console.error(e)
        show_error('Failed to retrieve your weekends list! Request failed!')
    });

Values of after_str and before_str variables hold string data (01.12.2021 and 31.12.2021).

Back-end Python:

def get_weekends_view(request):
""" This view returns a user's weekend list within a specified time frame """

form = GetAfterAndBeforeForm(request.POST)

if form.is_valid():
    after, before = form.cleaned_data['after'], form.cleaned_data['before']

    result = []
    for weekend in Weekend.objects.filter(user=request.user, date__range=(after, before)):
        result.append({'date': weekend.date.strftime('%d.%m.%Y'), 'status': weekend.get_status_display()})

    return {'status': 'ok', 'weekends': result}
else:
    return {'status': 'error', 'msg': 'Form filled incorrectly! ' + str(request.POST)}

Forms:

class GetAfterAndBeforeForm(forms.Form):
    after = forms.DateField()
    before = forms.DateField()

Answer №1

Give this a go:

Try using this code snippet:
await fetch('{% url "get_weekends" %}', {
    method: "POST",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
    },
    params: JSON.stringify({ after: after_str, before: before_str }),
});

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

Input the date manually using the keyboard

I am currently utilizing the rc calendar package available at https://www.npmjs.com/package/rc-calendar When attempting to change the year from 2019 to 2018 by removing the "9," it works as expected. However, when trying to delete the entire date of 1/15/2 ...

How to Condense a JSON Array using Google Apps Script

My current task involves flattening the JSON file provided below into an array structure: { "@context": "http://schema.org", "@type": "EventReservation", "reservationNumber": "IO12345", "underName": "John Smith", "reservationFor": [{ "@type" ...

Exploring ways to retrieve global variables within a required() file in Node.js

Imagine having 2 files: main.js, and module.js: //main.js const myModule = require('./module'); let A = 'a'; myModule.log(); //module.js module.exports = { log() { console.log(A); } } After trying to call myModule.log, ...

What do users think of the UI feedback when they click on a react-router-dom <Link/> component?

My current challenge involves: Developing a single-page application using react and react-router-dom When a user clicks on a <Link to={"/new-page-route"}/>, the URL changes and a new <Component/> starts rendering While React is fast, my new ...

Tips for enhancing undo/redo functionality when working with canvas drawings in React

Currently, I am working on implementing undo/redo functionality for html-canvas drawing on medical (.nii) images in a React application. The images consist of slices stored in a Uint8ClampedArray and usually have dimensions around 500 (cols) x 500 (rows) x ...

Explain the purpose of the describe() function in Mocha testing framework

Exploring Mocha has been a goal of mine and I recently came across this example in the documentation: var assert = require("assert") describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when ...

Revert Bootstrap 4 Sidebar to its Previous State Upon Navigating Back in the Browser with Recursive Expansion

Check out this HTML, CSS, Bootstrap 4 code that creates a collapsible sidebar menu with an accordion-style design: https://i.sstatic.net/2hPmd.png My Goal I want to achieve the following using either Bootstrap 4, jQuery, or JavaScript... If I click on ...

Developing ASP.Net MVC 3 ViewModels with seamless integration of JavaScript and personalized validation techniques

Attempting to develop a custom validation method for my application has been an interesting challenge. While it functions correctly on the server side, I am now exploring how to extend this validation to also work seamlessly with client-side unobtrusive Ja ...

Having trouble getting Apollo Server 2.0 to function properly with the join-monster-graphql-tools-adapter when using an Oracle

In the process of creating a graphql server using expressjs, I have implemented the following code snippet: const express = require('express'); const app = express(); const {ApolloServer} = require('apollo-server-express'); const serv ...

Incorporating Event Listeners for Controlling Playback and Navigation in HTML5 Video

I am trying to integrate an HTML5 video into my website to demonstrate how a product works. Each time a user clicks on an image, I want the video to skip to a specific time and then pause at another predefined time. However, the code I have implemented so ...

Testing the compose() function in ReactJS with JestJS and Enzyme: A guide for testing graphql() function integration

Currently, I am testing a basic reactJS component with react-apollo using jestJS and utilizing the coverage feature of jest. However, after running the coverage analysis, it has come to my attention that I have overlooked testing the line options: (props) ...

Sequelize hooks fail to trigger when manually updating records

As a newbie to sequelize and RDBMS, I recently incorporated a sequelize hook in the following manner bills.afterBulkUpdate((instance, options) => { console.log(instance); }); I am curious if updating any record in the bills table manually (via DB sc ...

Press the button to reveal the table - jQuery/JavaScript

Can you please provide guidance on how to hide the inner HTML table when the page loads and then display the table with results only after clicking the search button? I do not want to show an empty table. Below is the code snippet that I have tried: Howev ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

Checkbox with an indeterminate state in Angular

I'm currently working on updating an AngularJS (1.5) setup where a parent checkbox becomes indeterminate if one of its children is selected, and all the children are selected if the parent is selected. My main challenge lies in converting the old ES5 ...

What are the steps to creating an API for a web application?

I have been tasked with creating an API for my web application that will utilize another website's authentication system. While I have a basic understanding of JavaScript, PHP, and HTML, I need guidance on how to proceed with building the API. Here i ...

Limiting Velocity in a Two-Dimensional Spacecraft

Like many others diving into the world of programming, I decided to challenge myself with a spaceship game project. At this point, I have successfully incorporated parallax stars and other essential features expected in a space-themed game. The spacecraft ...

Where should the logic for the Redux app be implemented for optimal performance?

My react-redux app features an action-creator that filters a list of objects based on a specified title: export const filterItems = (title) => dispatch => { axios.get(`/api/items/?title=${title}`) .then(res => { dispatch({ ...

Navigate to a different page in NextJs and initiate a smooth scrolling effect using the react-scroll library

Utilizing the Next.js Link element in my React application: import Link from 'next/link'; Along with buttons that scroll to a specific element when clicked using: import { Link } from 'react-scroll'; https://www.npmjs.com/package/reac ...

Synchronizing live data from the database to the front end of a Java-powered web application

I'm currently developing a customer support web application using Java, where I need to display the status of "Customer Representatives (CR)" in the front-end - whether they are available, busy, or away on the phone. When a CR ends a call with a cust ...