简体   繁体   English

在 node.js 中 res.json 之后的 res.redirect

[英]res.redirect after res.json in node.js

I have the following code below I want to redirect and return the response as well, can someone help me in this?我在下面有以下代码,我也想重定向并返回响应,有人可以帮助我吗? What is the better solution for this?什么是更好的解决方案?

try {
  res.json(await example.preview(access_token, context, id, body))
  res.redirect(`${sso.host}/session/login?grant_type=bearer&access_token=${access_token}&remember_me=true&redirect_uri=${encodeURIComponent(
 'https://example.com'
 )}`);
} catch (e) {
  logger.info(e);
  next(e);
}

You can't.你不能。

It isn't possible (and simply doesn't make sense) to simultaneously say both:不可能(并且根本没有意义)同时说:

  • Here is the thing you asked for这是你要的东西
  • The thing you asked for is not here, you need to request this URL instead你要的东西不在这里,你需要改为请求这个网址

(This sounds like an XY Problem ; you might want to ask a new question about the problem you are trying to solve by asking how to do this impossible thing). (这听起来像是一个XY 问题;您可能想通过询问如何做这件不可能的事情来询问有关您正在尝试解决的问题的新问题)。

You can use res.json to return a regular 200 response, with any data you wish and also add a redirectURL item, which will be handled on the client side.您可以使用res.json返回常规 200 响应,包含您想要的任何数据,并添加一个redirectURL项,该项将在客户端处理。

Example on client side:客户端示例:

// Simulate a mouse click:
window.location.href = redirectURL;

// Simulate an HTTP redirect:
window.location.replace(redirectURL);

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

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