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

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

Merge three asynchronous tasks into a single observable stream

I have 3 different observables that I am using to filter the HTML content. Here is the TypeScript code snippet: fiscalYear$ = this.store$.select(this.tableStoreService.getFiscalYear); isLoading$ = this.store$.select(this.tableStoreService.tableSelector ...

jade - implementing conditional logic

How can I achieve the following if condition in jade? each item,count in display if(count % 3 === 0) { ul.thumbnails } li.span6 //nested under ul //more code nested under li I have sea ...

Retrieving values from res.send in Jade Template

Having recently delved into the world of node.js and Jade, I've been teaching myself through tutorials on udemy. However, I'm facing some challenges when trying to integrate Jade, Express, and Backbone based on an example. I attempted to use res. ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

My jQuery form is not functioning properly upon initialization

Let's take a look at this sample 'template' code: $(document).on("<EVENT>", "form", function() { $(this).find(".input input").each(function() { var required = $(this).attr("required"); var checkField = $(this).clos ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

AWS Lambda Error: Module not found - please check the file path '/var/task/index'

Node.js Alexa Task Problem Presently, I am working on creating a Node.js Alexa Skill using AWS Lambda. One of the functions I am struggling with involves fetching data from the OpenWeather API and storing it in a variable named weather. Below is the relev ...

Using EJS to Render a Function Expression?

Has anyone been able to successfully render a function call in express using EJS? Here's what I've tried so far: res.render("page", { test: test() }); Can someone confirm if this is possible, or provide guidance on how to call a function fr ...

Trying to replace all instances of a word in an HTML document with a <span> element, but only for <p>, <span>, and <div> tags. It shouldn't work if the parent node already contains

Here is the HTML code snippet I am working with: <div> hello world <p> the world is round <img src="domain.com/world.jpg"> </p> </div> I am looking to replace the word "world" (or any mixed case variations) with < ...

Unlocking the WiFi Security Key and Accessing Connected Devices with Javascript

When utilizing the command line netsh wlan show interfaces, it displays various information. However, I am specifically interested in extracting the data Profile : 3MobileWiFi-3D71. My goal is to retrieve only the content after the : so that ...

When using $.getJSON and $.ajax, the expected JSON object is not being returned

Currently, I am taking on the "local weather" front-end development challenge on freecodecamp.com. However, I'm facing some challenges when it comes to making an API call to fetch weather data from various weather APIs. This particular task requires r ...

Unable to use NodeJS await/async within an object

I'm currently developing a validation module using nodeJs and I'm facing difficulties understanding why the async/await feature is not functioning correctly in my current module. Within this module, I need to have multiple exports for validation ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Once upon a time in the land of Storybook, a mysterious error message appeared: "Invalid version. You must provide a string

I keep encountering an issue while attempting to set up storybook. Can anyone help me figure out what's causing this problem? npx storybook@latest init • Detecting project type. ✓ TypeError: Invalid version. Must be a string. Got type "obje ...

I'm struggling to understand the folder arrangement and the system is telling me it can't locate my file

I'm having trouble identifying what might be causing issues with my file structure. Currently, I am using Aurelia for the front end and node for the server. I attempted a fix by performing a join operation, which resolved some of the problems. However ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...