'Express not redirecting to desired page

I am using post request to save the filter parameters in a local json file for next page . But after writing in the file my redirect is not working, it goes directly to login page .If I comment out the writing part , it just works fine.

function writeToFile(data){
    fs.writeFile('filters.json',data)
}
app.post('/mentor/taskManager/:portal',(req,res)=>{
    const { portal } = req.params;
    writeToFile(JSON.stringify(req.body))
    res.redirect(`/mentor/taskManager/${portal}`)
})


Solution 1:[1]

I guess you have a callback error from your code.

According to https://nodejs.org/api/fs.html#fswritefilefile-data-options-callback, you need to have a callback to check the write file method.

I suggest you change your writeToFile function become like this

function writeToFile(data) {
    fs.writeFile("filters.json", data, (err) => {
        if (err)
            console.log(err);
        else {
            console.log("File written successfully\n");
        }
    });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 taipei