Error 404: "Headers already sent to the client cannot be modified"

I'm currently developing a Node/Express application and I want it to display a 404 page if a promise function doesn't resolve.

This is my approach:

app.get("/projects", t("projects", function(req, res) {
    res.header("Cache-Control", "private, max-age=0, no-cache, no-store");
    return projects.list(req.user, req.query)
        .then((projects) => (Object.assign(projects, { company_name: req.user.company_name })))
        .catch(() => res.status("404").send(""));
}));

However, this causes the app to crash with the error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
.

Is there a way to make it return a 404 without crashing the app only when the promise rejects?

Just for reference, the projects.list function is quite simple, it just performs a database query and returns an object.

function list(user, query_params) {
    const folder = query_params.folder || "all";
    return entity.User.listedProjects(user.id, filter_by)
        .then((projects) => {
            if (folder !== null && !projects.some(t => t.current)) {
                return Promise.reject();
            }
            return {
                "projects": projects,
                "active_folder": folder
            };
        });
}

UPDATE: here's the definition of the t function as requested:

function t(template_name, get_additional_params, options={}) {
    return function(req, res) {
        if (!req.user && !options.do_not_require_login) return res.redirect("/login?redirect=" + encodeURIComponent(req.originalUrl));

        if (!get_additional_params) {
            get_additional_params = (() => Promise.resolve({}));
        }

        get_additional_params(req, res)
            .then(function(additional_params) {
                if (additional_params && "_redirect" in additional_params) {
                    return res.redirect(additional_params._redirect);
                }

                const standard_params = {
                    "error": req.flash("error"),
                };

                const params = Object.assign({}, additional_params, standard_params);
                res.render(template_name + ".html", params);
            })
            .catch(utils.fail(req, res));
    };
}

Answer №1

.catch(...) will result in a resolved promise, indicating that within your t function you may be attempting to send extra headers.

To provide a quick solution, you can replace your catch block with:

.catch(err => {
  res.status("404").send("");
  throw err;
});

This adjustment will prevent your t function from trying to set additional headers.

Answer №2

When accessing the "/projects" route, a function called "t" is triggered with the alias "projects". This function takes in a request and response parameter.

Within this function, the projects are listed based on the user's credentials and query. The company name associated with the user is also added to the projects using Object.assign method.

After listing the projects, the response header is set to ensure no caching by specifying "Cache-Control" as "private, max-age=0, no-cache, no-store".

If an error occurs during the process, a status code of 404 is sent back with an empty response.

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 tablet is having trouble playing the mp3 audio file

When clicking on an mp3 audio file, I want the previous file to continue playing along with the new one. While this works perfectly on browsers with Windows machines, there seems to be an issue when using a tablet. The second mp3 stops playing when I clic ...

If the user decides to change their answer, the current line between the two DIVs will be removed

After clicking on two DIVs, I created two lines. Now, I am facing an issue with resetting the unwanted line when changing my answer. To reset the line, you can refer to the code snippet below: var lastSelection; ...

What is the best way to retrieve a JSON key in ReactJS?

I am currently facing a rendering issue. In my componentDidMount function, I am using axios to make a GET call and then updating the state with the received JSON data. The problem arises when I try to access the keys of the JSON in the render method becau ...

Switch between two tabs with the convenient toggle button

I have implemented 2 tabs using Bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" role="tab" data-toggle="tab">CLient</a></li> <li role="presentatio ...

Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal. let obj = { doc_id: sessionStorage.getItem('doc_id'), batch_no: sessionStorage.getItem('batch_no') } I attempted to make adjustments by a ...

Is there a way to showcase an epub format book using only HTML5, CSS, and jQuery?

Can ePub format books be displayed in a web browser using only HTML5, CSS, and jQuery? I would appreciate any suggestions on how to accomplish this. Additionally, it needs to be responsive so that it can work on iPad. While I am aware of this requirement, ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...

Using Vuejs to pass the SAVE function into a CRUD component

I am facing a challenge in finding a suitable solution that involves advanced parent-child communication in Vue.js. The scenario is such that there are multiple parent components, each with its own logic on how to save data. On the other hand, there is onl ...

I am unable to make changes to the Text Field component in Material-UI

After developing a React App using Material-UI, I decided to create independent Components. Below are the independent components (<PanelDiv/>): render() { return ( <div className="panelDiv-component" style={{display:this.prop ...

Switch between showing and hiding a div by clicking on an image

Currently, I am experimenting with the toggle div function and utilizing images as triggers for toggling. For instance, when a div is closed, an image of a "plus" sign indicates to the user that it can be expanded, and vice versa for compressing the div. T ...

Storing complex data structures in Firebase using VUEX

I am struggling to properly store my 'players' data within my team data structure. Currently, it is being saved with the team id but I need it to be nested inside of teams. Essentially, I want the players to seamlessly integrate and be appended ...

Why does Array Object sorting fail to handle large amounts of data in Javascript?

Encountered an issue today, not sure if it's a coding problem or a bug in Javascript. Attempting to sort an object array structured like this: const array = [{ text: 'one', count: 5 }, { text: 'two', count: 5 }, { text: 'thre ...

When the mongoose find query returns no results, execute the if-else condition

Currently in the process of developing a node.js/express/passport application utilizing Mongoose for DB calls. The main issue at hand involves verifying whether query results exist, as it seems to indicate there are results even when none are present! Sn ...

Headers are being removed by Express or React

I currently have a basic setup using React and Express. I am in the process of adding headers to a response, but some are not appearing in the React app. On the Express side... app.post('/api/createpdf', (req, res) => { console.l ...

Looking to simplify the complex JSON structure by converting it into an array using JavaScript

Being a newcomer to javascript, I am struggling with breaking down a complex structure into an array. The current structure is as follows: [ { "Key": "ProducePRINKA0370001", "Record": { "docType": "Produce", "PR ...

Ways to access UserProfile in a different Dialogio

For the implementation of a chatbot, I am utilizing Microsoft's Bot Builder framework. However, upon implementing an alternative path to the dialog flow, I noticed that the user's Profile references are getting lost. Here is the code snippet fr ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Where do I begin on this uncharted journey of self-expression?

As I dive into learning node/express, I've acquired some books and followed online guides to get started. While I have created a basic app using the express command line tool with two routes defined in my app.js file, app.get('/', routes.in ...

What is the best way to store a personalized configuration for a user within a Node module?

For my CLI project in Node.js utilizing commander.js, I am interested in implementing a way to store user-specific configuration settings. This will allow users to input their preferences only once during the initial usage. What would be the best approac ...