简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM