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

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...

Issues arise with User obj's utilization of the Instagram API

After setting up my Instagram developer account, I was able to obtain the client_secret and client_id. Authentication went smoothly for my own user (myusername), and I received an access_token. However, when attempting to utilize this endpoint TOKEN] Fo ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...

Conceal the div if it remains unhidden within the following 10 seconds

This piece of code is designed to show a loader image until the page finishes loading. Here is the code snippet: document.onreadystatechange = function () { var state = document.readyState if (state == 'interactive') { $('#unti ...

Having Trouble with Updating Variables in AngularJS Service

I am faced with a challenge involving a series of images displayed side by side. My goal is to determine which image has been clicked, retrieve the relevant information, and display it in a modal window. HTML Markup <section class="portfolio-grid ...

Submitting information retrieved through an AJAX request to a MySQL database using PHP

I have implemented a JavaScript function to collect and display data, but now I am looking to save this data into a MySQL database for tracking purposes. I attempted to connect to the MySQL database locally using PHP code, but encountered some issues. I be ...

Resetting the selected options in AngularJS dropdown lists

Utilizing ng-repeat in my HTML code to iterate over a JavaScript array and displaying it within a selection. I am trying to achieve the functionality of clearing all selected data from these dropdown lists when a button is clicked. Snippet of HTML: <d ...

Determine if the website is reachable

Is there a way to verify the online status of a particular website? The website's name is entered into an input field and sent via post. Although there is an NPM module for pinging hosts, it does not provide much help in my situation. I need a soluti ...

Encountering the issue "Converting circular structure to JSON" when handling express and mongodb in my project

I'm currently working on a project to identify tours within a specific distance, and here is the code I have so far: exports.getTourWithin = catchAsync(async (req, res, next) => { const { distance, latlng, unit } = req.params; const [lat, lng] ...

Using ng-mouseover along with ng-if and an animated class causes issues

Whenever I hover over a link, it triggers a change in a variable value which then displays a <p> tag using ng-if. The code snippet looks like this: <div class="position text-center" ng-mouseover="social=1" ng-mouseleave="social=-1"> &l ...

Transferring sizable JavaScript array to the Web API

I've been grappling with this problem for two days... In my JavaScript code, I have a large array comprising 20,000 rows and 41 columns. This data was initially fetched in JavaScript via an ajax call, as shown below: var dataArray = []; var dataRequ ...

Is there a way to set a default value for an Angular service provider?

Imagine an Angular Service that encapsulates the HTTP Client Module. export class HttpWrapperService { private apiKey: string; } Of course, it offers additional features that are not relevant here. Now I'm faced with the task of supplying HttpWr ...

Utilizing the Jquery datetimepicker (xdsoft) to dynamically limit the date range between two inline datepickers

Check out the Jquery datepicker plugin available here: We previously had a setup where we could dynamically restrict the date range with two datepickers when text inputs are clicked on. However, the client now wants the calendars to be displayed inline, c ...

Is your script tag not functioning properly with Promises?

Below is the code snippet used to dynamically append scripts in the DOM using promises. This piece of code is executed within an iframe for A-frame technology and it is generated using Google Blockly (Block-based coding). export const appendScript = asy ...

Sorting an array based on shortest distance in Javascript - A step-by-step guide

I need to organize an array so that each element is in the closest proximity to its previous location. The array looks like this: locations=[{"loc1",lat,long},{"loc2",lat,long},{"loc3",lat,long},{"loc4",lat,long},{"loc5",lat,long}] Here's the funct ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

What is the process of transforming async/await code into synchronous code in JavaScript?

Blocking the event loop is generally considered bad practice due to its consequences. However, even the native fs module includes some synchronous functions for specific purposes, such as CLIs using fs.readFileSync. I am interested in converting the follo ...

What is the best way to showcase navigation and footer on every page using AngularJS?

I'm in the process of building a Single Page Application. I've decided to create separate components for Navigation, Section, and Footer. The Navigation and Footer should be displayed on every page, while only the Section content changes when nav ...

Changing the Color of an Object3D Mesh in Three.js

Seeking advice on how to update the color of a Three.js Object3D. Initially created using MeshStandardMaterial, this object is later retrieved from the scene by its ID. Is it possible to change the color of the Mesh at this stage? If needing to replace th ...

Several socket.io sessions have been initiated

I'm fairly new to working with node.js and currently attempting to set up a server using socketio to send messages to the frontend (React). However, when running the server and multiple connections are being established, I encounter the following outp ...