Unable to execute a GET request using the Fetch API on Django REST Framework results in receiving an HTTP 304 error code

When attempting a GET request with the Fetch API (Node Fetch) module against a Django REST API, I am encountering a 304 error. I am unsure of how to resolve this issue as it seems to be related to requesting the same data repeatedly. Is there no way around this? How can I store or handle this information differently?

Below is the code for a controller in Express.js:

postsController.index = (req, res, next) => {
    try {
        let postsResponse = fetch('http://localhost:8000/api/posts.json', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json"
            },
        })
        .then(response => {
            return response.json()
        })
        .catch(err => {
            next(res)
        })

        postsResponse.then((result) => {
            res.render('newspapers/index', { title: 'Posts', posts: result })
        })
    } catch (error) {
        next(error)
    }
}

Error message:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
express_1  |     at ServerResponse.setHeader (_http_outgoing.js:535:11)
express_1  |     at ServerResponse.header (/var/www/app/node_modules/express/lib/response.js:767:10)
express_1  |     at ServerResponse.contentType (/var/www/app/node_modules/express/lib/response.js:595:15)
express_1  |     at ServerResponse.send (/var/www/app/node_modules/express/lib/response.js:145:14)
express_1  |     at done (/var/www/app/node_modules/express/lib/response.js:1004:10)
express_1  |     at Object.exports.render (/var/www/app/node_modules/jade/lib/jade.js:206:5)
express_1  |     at View.exports.renderFile [as engine] (/var/www/app/node_modules/jade/lib/jade.js:233:13)
express_1  |     at View.render (/var/www/app/node_modules/express/lib/view.js:135:8)
express_1  |     at tryRender (/var/www/app/node_modules/express/lib/application.js:640:10)
express_1  |     at Function.render (/var/www/app/node_modules/express/lib/application.js:592:3)

I have tried going to the network tab in Chrome and selecting "disable cache," which resulted in a successful 200 OK status. However, I am still seeing a traceback of the aforementioned problem. Can anyone provide insight into what this means?

Answer №1

Issues above the 300 range typically involve redirection.

redirect: 'follow'

This means you should likely follow the redirect, unless this behavior is unintentional and there's a misconfiguration in your downstream service.

        let postsResponse = fetch('http://localhost:8000/api/posts.json', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json"
            },
+++         redirect: 'follow'
        })
``

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 webpack production build consistently displays the message "This site is running on the development build of React."

I have been attempting to utilize webpack-4 for generating a production build of my React project (not built with Create React App), but I am facing difficulties. The project is written in TypeScript and uses ts-loader, as well as React version 15.6.2. Be ...

Is there a way to display the inbox area upon completion of the document loading process?

I'm currently working on creating an inbox feature for my personal portfolio, mostly as a learning exercise rather than for any practical use. However, I've run into an issue where all emails are being displayed by default when the page loads wit ...

Conceal a button using an AJAX POST request

I'm encountering an issue with my Ajax post where I am trying to disable the button used to submit data. I've reviewed my code and it seems accurate, but the button is not getting disabled. I attempted using $("#refreshButton").attr("disabled", t ...

What is an alternative way to display static images in Rails 5 without relying on the Asset Pipeline?

I developed a web-based application with the backend built on Rails 5. Utilizing AngularJS for the frontend, I opted to not use the Asset Pipeline to deliver static content. Instead, I loaded all my scripts (JS & CSS) in the index.html file located within ...

Remove objects from an array if they share identical key values

I'm having trouble getting this to work. I have an array of objects that looks like this: let myCities = [ { value: 'Barcelona', code: 02342837492482347 }, { value: 'Rome', code: 28282716171819 }, { v ...

Trouble with Map method not displaying data in Next.js

I am currently working on a Map Method but facing an issue. The data 1,2,3,4,5 is successfully displayed in the console.log, but not showing on the website. import React from 'react' export default function secretStashScreen() { const numbers = ...

The infinite scroll feature on Next.js resulted in duplicating the last element during the initial fetch process

I have a project that involves fetching data from Strapi Rest API using Next.js. I am fetching and displaying cards based on the fetched content. To prevent loading all the data at once, I have implemented an infinite scroll feature using react-infinite-sc ...

Performing a sequence of actions using Jquery Queue() function and iterating through each

I am facing an interesting challenge with an array called result[i]. My goal is to iterate through each field in the array and add it to a specific element on my webpage. $("tr:first").after(result[i]); However, I would like this process to happen with a ...

Floating action button within a collapsible panel

I am having trouble placing a fixed-action-btn inside a collapsible body. It keeps appearing in the bottom right corner of the page instead of within the collapsible itself. How can I ensure that the button stays inside the body? Check out this link for r ...

Error: The 'length' property cannot be searched for using the 'in' operator

Hmm, I keep getting an error that says "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" Every time I attempt a $.each on this JSON object: {"type":"Anuncio","textos":["Probando ...

Adding an image to a PDF file using NodeJS and Pdfmake

I am currently using the pdfmake api in my NodeJS application to generate PDF files. However, I am facing an issue when trying to add an image to the document as I keep receiving the following error message: Error: Invalid image format. The images dictiona ...

Guide on redirecting unauthenticated users using express-jwt

I am currently working on my first Express app and I'm in the process of implementing authentication for certain routes. My goal is to redirect users to the home page if they are not authenticated. Below is the middleware I have written: var jwt = re ...

Guide to increasing a field value in Backendless.com

Below is an overview of the table structure I have: Table data ---------------------------------- - User - ---------------------------------- | objectId | name | password | ---------------------------------- | z12ttttt | ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

Transforming Color with JQuery on the Fly

Check out this Jquery script that gradually changes the color of an object from (0, 0, 0) to (255, 255, 0). $(document).ready(function(){ var r = 0; var g = 0; changeColor(r, g); }); function changeColor(r, g){ var newColor = "(" + r + ", ...

Tips for automatically filling out a div class form:

I currently have an Autoresponder email form featured on my webpage. Here is a snippet of the code for the section where customers enter their email: <div id = "af-form-45" class = "af-form" > <div id = "af-body-45" class = "af-body af-standa ...

Scrolling text blocks on mobile devices

When viewing the website on a desktop, everything works perfectly. However, when accessing it on a mobile device and trying to scroll down, only the text moves while the page remains stationary. The website utilizes skrollr core for animations. I have alre ...

Having trouble with managing state changes in a React application using Multiple Checkbox components from M

Trying to update the state of multiple checkboxes and then send a POST request. Visually, the checkboxes change, but the form data remains unchanged. Here is the code snippet: export default function AccountInformations(props) { // const { enqueueSnack ...

Top method for identifying "abandoned words" within text that has been wrapped

Our content and design teams have a specific request to prevent paragraphs from ending with an "orphan word" - a single word on the last line of text that has wrapped onto multiple lines. The designer's proposed solution is to adjust the margins sligh ...

Chrome Developer Tools - Array Length Discrepancies

While exploring Chrome DevTools, I came across an inconsistency that caught my attention. The screenshot above shows the issue I encountered. Initially, it indicated that the object contained a Body and a Head, with the head being an array of length 1. Ho ...