error encountered in NestJS: unable to modify headers once they have been sent

request /login/login.html

redirect /login

I made a change to the redirect within the interceptor

export class UricheckInterceptor implements NestInterceptor {
    constructor(private uri: string[]) {}
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const response = context.switchToHttp().getResponse();
        const request = context.switchToHttp().getRequest();
        const { pathname } = parseurl(request);
        const pathLength = pathname.length;
        const pathSlash = pathname.lastIndexOf('/');
        const pathLast = pathname.substring(pathSlash + 1, pathLength);
        const queryString = request.query;
        if (pathLast === this.uri[1]) {
            if (Object.keys(queryString).length > 0) {
                if (queryString.code !== undefined && queryString.bst !== undefined) {
                    response.redirect(301, `./${this.uri[0]}?code=${queryString.code}&bst=${queryString.bst}`);
                    next.handle();
                } 
        } else {
            return next.handle();
        }
    }
}

An error occurs when the redirect is executed.

This error occurred due to throwing inside an async function without a catch block or rejecting a promise that was not handled with .catch(). The promise was rejected with the following reason:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client....

I am struggling to resolve this issue on my own.

Your assistance would be greatly appreciated.

Can you help me identify what went wrong?

Answer №1

It's important to note that your header is actually being included in the response, but it won't be visible once the browser follows the redirect and requests the new URL. Browsers simply don't display those headers. When you use res.redirect(), a response with a 301/302 status and a location header is sent. The browser picks up on this status code and header, then initiates a new request to your server for the redirected location. Any headers from the previous or subsequent responses are NOT carried over to the new request for the redirected location.

If you need to pass data during a redirected request, there are some common methods:

  1. Add the data to the query string of the redirected URL as a parameter. This way, your server can access the query string upon receiving the redirected request.
  2. Utilize cookies to store the data. Your server can examine the cookie when the redirected request arrives.
  3. Store the data in a server-side session object that can be accessed in the following request. Your server can then reference the session data when processing the redirected request. Note that only the first option (query parameter) is considered completely secure, as the other methods may lead to confusion regarding which request the data corresponds to if multiple requests are made by the same user.

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

Stripping double quotes from json output

Using a basic array to reference icons like so: {name: "text", avatar: srcs[15]} has been working perfectly. However, I am now dynamically creating an array from my JSON API, resulting in an array of objects structured like this: {name: "text", avatar: ...

Is the entire web page generated on the server with each request using getServerSideProps()?

As I understand it, getServerSideProps will dynamically generate the complete page on every request, rather than pre-building it. But does getServerSideProps always generate the entire page upon each server request, or only when the data in the database ha ...

JSON - When an Object's Value Matches

Within my JSON file, I have an object that contains an array of nested objects. I am looking for a way to trigger a function based on the value of a specific object. If the value matches a certain number, I want to display only those objects within a desig ...

Using regular expressions to replace a string with the captured text

I am trying to replace all non-alphanumeric characters in a string with themselves enclosed in square brackets "[ ]". This is what I have attempted: var text = "ab!@1b*. ef"; var regex = /\W/g; var result = text.replace(regex, "[$0]"); console.lo ...

The Best Way to Display Quad Wireframe in Three.js using OBJ Model

I am trying to display the wireframe of OBJ meshes using Three.js. However, Three.js can only render triangles, so I came up with the idea of creating a line for each edge of the model. After parsing the OBJ file and iterating through its vertices and fac ...

Divide the Javascript code from the HTML Canvas

I have been diving into HTML5 Canvas and exploring how to implement it using Javascript code. However, I am facing difficulties separating the Javascript code from the original html file. Despite trying some solutions: HTML5 Canvas not working in extern ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...

Switch between adding elements to various div containers

Can we implement a functionality where clicking an anchor tag moves the .item from .region1 to .region2, and then moving it back to .region1 when clicked again? Essentially creating a toggle behavior? <a href="#" class="btn">Click</div> &l ...

What if the v-on:click event is applied to the wrong element?

I'm attempting to manipulate the anchor tag with jQuery by changing its color when clicked, but I'm struggling to correctly target it. <a v-on:click="action($event)"> <span>entry 1</span> <span>entry 2</span> ...

Error Loading JQuery: The function $() is not recognized in the Shopify platform

I seem to be overlooking something obvious. I am using Shopify and have included jQuery in the head section of the theme.liquid file: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> This script is placed rig ...

Displaying nested arrays correctly

My latest endeavour involves constructing a data tree in Vue, utilizing components. Let's examine the provided data snippet: "data": [ { "id": 1, "name": "foo", "children": [ { "id": 2, "name": "bar", "children": [] } ...

Save the environment value within Vue when the app starts up

When working with a basic web app created using VueJS, the application makes an API call that returns an object containing the environment name. For instance: https://appsdev/mysimpleapp/api/environment returns {"applicationName":"My S ...

Error encountered during execution of Angular application, specifically TS2305 error?

Hello, I am currently running an angular application by using the 'ng serve' command. I encountered the following error: ERROR in src/app/accounts/account-form/account-form.component.ts(29,3): error TS2305: Module '"/home/prasanth/primecas ...

render target in three.js EffectComposer

When we utilize an EffectComposer, the scene is rendered into either composer.renderTarget2 or composer.renderTarget1. In a particular example, I came across this: renderer.render( scene, camera, composer.renderTarget2, true ); renderer.shadowMapEnabled ...

Node.js: implementing method overriding

I'm currently exploring the most effective method to override a function in a custom module using node.js. As part of my project, I am developing a custom middleware that will assist me in automatically loading various custom modules such as security ...

Creating a dynamic quiz with random images using text boxes in HTML and PHP

I am working on creating a 'guess the picture' style quiz where a random image is displayed as the question, and users must input their answer in a textbox. The question will be selected randomly from 3-5 options each time the page is refreshed o ...

Library of User Interface components for React Native applications

As I embark on my journey of building my first major app using React Native, a question comes to mind. Is there a UI framework available for React Native that offers pre-styled components right out of the box? Similar to how Ionic provides a base theme a ...

Removing a checker piece in the game of checkers after successfully jumping over it

Recently completed a game of checkers and managed to figure out the logic for moving and jumping checker pieces. However, I'm now facing an issue with implementing the logic for removing or deleting a jumped-over checker piece. How can I automaticall ...

What is the best method to extract information from JavaScript tables using Python and Selenium?

As a beginner in Python, JavaScript, and Web-Scraping, I am facing the challenge of extracting data from tables on a specific webpage (https://www.mcmaster.com/cam-lock-fittings/material~aluminum/) and saving it into a csv file. https://i.sstatic.net/xQBO ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: https://i.sstatic.net/GXjur.png But I want this instead: https://i.sstatic.net/spcS2.png Does morris.js support this feature? If not, what would be the most effective method to implement it? ...