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

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

(node:2072) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (internal/errors.js:322:7)
    at ServerResponse.setHeader (_http_outgoing.js:561:11)
    at ServerResponse.header (E:\codes\node\day-07\blogs\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (E:\codes\node\day-07\blogs\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (E:\codes\node\day-07\blogs\node_modules\express\lib\response.js:267:15)
    at ServerResponse.send (E:\codes\node\day-07\blogs\node_modules\express\lib\response.js:158:21)
    at module.exports (E:\codes\node\day-07\blogs\route\admin\user-edit-fn.js:17:9)
    at Layer.handle [as handle_request] (E:\codes\node\day-07\blogs\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\codes\node\day-07\blogs\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (E:\codes\node\day-07\blogs\node_modules\express\lib\router\route.js:112:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2072) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

Cause: the joi code is updated, and the syntax of the old version leads to an error

Solution:

//import joi moudle
const Joi = require('joi')

module.exports = async(req, res) => {
    //Define the validation rules for the object
    const schema = Joi.object({
            username: Joi.string().min(2).max(10).required().error(new Error('username does not match the rule')),
            email: Joi.string().email().required().error(new Error('Email format does not match the requirements')),
            password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('Password does not match the rules')),
            role: Joi.string().valid('normal', 'admin').required().error(new Error('Role value does not match the rule')),
            state: Joi.number().valid(0, 1).required().error(new Error('State value does not match the rule'))
        })
        // use try{}catch(){} statements to catch exceptions for asynchronous functions
    try {
        //implement validation
        await schema.validateAsync(req.body)
    } catch (e) {
        //Validation did not pass
        //e.message
        //redirect back to the user add page
        res.redirect(`/admin/user-edit?${e.message}`)
    }

}