return res.redirect() not working in expressJs

28 Views Asked by At

I am trying to run a series of asynchronous operations in an expressJS controller and redirect to homepage with a flash message when all operations are complete. All the async operations execute successfully but it does not redirect to homepage. I even added a log to check if the req.flash is the problem but it isn't, the res.redirect just doesn't work. This is the sample of the controller code below. Please what could be the issue or what could i be doing wrong?

module.exports.operationController = async(req, res) => {
const { opId } = req.body;

try {
    var operationResult = {
        operate: false,
        work: false,
        remark: ''
    }

    const operation = await Operation.findById(opId);
    
    const fulldate = operation.operationdate + 'T00:00:00.000Z';
    const datedate = new Date(fulldate);
    const operationTime = datedate.getTime();
    const today = Date.now();
    const oneweek = 604800000;

    // Check if operation is atleast 1 week old 
    if ((today-opertionTime) < oneweek) {
        operationResult.operate = true;
        operationResult.work = false;
        operationResult.remark = 'Undue operation assessment';
    } else {
        const checkOperation = await opCheck(operation);
        log(checkOperation);
        operationResult.operate = checkOperation.operate;
        operationResult.work = checkOperation.work;
        checkOperation.remark = checkOperation.remark;
    }

const assessedOps = await new AssessedOperations({
    op_id: operation._id,
    op_work: operationResult.work,
    op_remark: operationResult.remark,
    op_manager_id: operation.manager.Id
});

const savedAssessedOps = await assessedOps.save();

const opsupdate = await Operation.findByIdAndUpdate(operation._id, {assessedoperation: savedAssessedOps._id});
const updatesave = await updatesave.save();
    
if (updatesave) {
    opAnalysisReport(operation, savedAssessedOps._id);
    req.flash("message", `Operations Assessed!`);
    console.log('after flash');
    return res.status(201).redirect("/");
}   

} catch(err) {
    return res.render('errorpage');
}
}
1

There are 1 best solutions below

0
slebetman On

Because you did this:

return res.status(201);

This makes it impossible to set the status to 301, 302 or 308 (what redirect means in HTTP, see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections)

You are basically trying to do this:

return res.set('Location','/').status(201).status(302);

Because you have already set the status to 201 you cannot set the status a second time to 302 (redirect). The status 201 is clashing with .redirect()