简体   繁体   English

express js无法在res.redirect之前设置res.json

[英]express js cannot set res.json before res.redirect

hello im using express module in node JS你好我在节点 JS 中使用 express 模块

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:我必须先发送一些 json 数据然后重定向..但我收到此错误:
node:_http_outgoing:576节点:_http_outgoing:576


throw new ERR_HTTP_HEADERS_SENT('set'); 抛出新的 ERR_HTTP_HEADERS_SENT('set'); ^ ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头
can anyone please help, thank you谁能帮忙,谢谢

you can include "redirect" as a property within json, for instance:您可以将“重定向”作为 json 中的一个属性,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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