Home > Enterprise >  express js cannot set res.json before res.redirect
express js cannot set res.json before res.redirect

Time:03-09

hello im using express module in node JS

res.json({ auth: true, token: token, message: "success" });
res.redirect('/');

i have to send some json data first then redirect ..but i'm getting this error:
node:_http_outgoing:576


throw new ERR_HTTP_HEADERS_SENT('set'); ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
can anyone please help, thank you

CodePudding user response:

you can include "redirect" as a property within json, for instance :

res.json({ auth: true, token: token, message: "success", redirect : "/whatever/go"});

then, on the client side you can perform the redirecting like this :

fetch(url)
      .then(res => res.json())
      .then(body => window.location.href = body.redirect)
      .catch(err => console.log(err));
  • Related