express js cannot set res.json before res.redirect

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x