Solution for How to render and redirect together in ExpressJS
is Given Below:
I am working on ExpressJS to build my website’s backend and it calls my API to create a response.
However I need to show that payment was successful and then redirect automatically redirect after the a resource has been created on AWS. I am using websockets for this as this takes some time to happen.
But when I use res.render(),then call the API and if status is 200 use res.redirect() to go to another page. But when I do this I get this error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
to the client
at new NodeError (node:internal/errors:370:5)
at ServerResponse.setHeader (node:_http_outgoing:573:11)
I know the error is because I am calling res.redirect() after res.render(), but I don’t know any other solution to my problem.
Could someone please tell me how to do this?
Code snippet:
res.render('success.ejs')
console.log("Calling websocket endpoint: ", wsData)
aws.websocketHandler(ws_data)
.then(async (resp_data) => {
let data = await resp_data;
console.log("Status: ", data.status_code)
if (data.status_code === 200) {
return data
}
}).then((data)=>{
console.log(data)
res.redirect("/dashboard")
})
What other approach can I take?
Any help would be greatly appreciated!
You already know the problem so i’ll just provide an alternative.
Instead of using res.redirect
, you can just emit a JSON response and handle it from the client’s side. For example,
...
}).then((data)=>{
console.log(data)
//res.redirect("/dashboard") is now commented
let json_data = {redirect_url:"/dashboard"}
client.emit('redirect',json_data)
})
Then on the client side, you write,
socket.on("redirect",(data)=>{
let location = data.redirect_url
// write function to notify user of redirect
setInterval(()=>{
window.location.replace(location)
},3000)
})