简体   繁体   中英

Cannot set headers after they are sent to the client backend error

I created a simple backend function which should run through different checks for dates which are sent from the frontend.

 async checkVacation(req: Request, res: Response) {
        try {
            let currentUser = req.user as User
            let dates = this.getBodyDates(req.body)
            if (dates.start == null || req.body.end == null ||this.beforeTodayCheck(dates.start.toString()) ==true ) {
                res.status(400).send("Start and/or End date is invalid")
            }
            let vacationDays = await this.getDBVacationDay(dates.start, dates.end, currentUser.Id)
            res.send(vacationDays)
        } catch (err) {
            console.error(err)
            res.status(400).send(err)
        }
    }

So basically this function should check if the given dates are null and if the given start date is before today. As soon as I provide some invalid dates, the backend gives me those errors

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

I dont know how to handle this error. Greetings, Leo

Putting this into an "answer" rather than a comment. As Ricky Mo stated, this occurs because of the multiple uses of res.send() .

This can be avoided by changing it to return res.send() which will ensure only one will ever get ran.

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM