Home > Blockchain >  nestjs redirect error: can't set headers after they are sent
nestjs redirect error: can't set headers after they are sent

Time:07-04

request /login/login.html

redirect /login

I change the redirect at 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();
        }
    }
}

The redirect proceeds and an error occurs.

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client....

I can't solve it at all.

I sincerely hope for your help.

What did I do wrong?

CodePudding user response:

Your header is likely being sent with the response, but you won't see that header when the browser actually follows the redirect and then requests the new URL. Browsers don't do that. Remember, when you do res.redirect(), it sends a response with a 301/302 status and a location header. The browser sees that 301/302 and reads the location header and then makes a new browser request to your server for the redirected location. Headers from the previous or next response are NOT added to the new request for the redirected location.

The usual ways to pass data like this to a redirected requests are:

  1. Put it in the query string for the redirected URL as a parameter. Your server will then see that query string when the redirected requests comes in.
  2. Set a cookie. Your server can then look at the cookie when the redirected request comes in.
  3. Set data in a server-side session object that can be accessed on the next request. Your server can then look at the session when the redirected request comes in. Only the first option above (query parameter) is entirely safe because the others can get confused about which request the data belongs to if there are other requests coming in from that same user.
  • Related