认证后如何从后端重定向到前端

How to Redirect From Backend To FrontEnd after Authentication

我的后端 (nodejs) 运行 在另一个端口上,我的前端 (React) 运行 在另一个端口上...所以在将凭据发送到后端并进行身份验证之后...如何我可以重定向到前端吗?

res.writeHead(302, {
    Location: 'http://front-end.com:8888/some/path'
});
res.end();

如果您指定完整 url,您可以使用 NodeJS 重定向到另一个端口。

您可以在 nodejs 中使用 web API (Express JS) 来构建 web api 和前端任何将向后端发送 HTTP 请求的 plainJS 或 modren 库。它会帮助更多。

在你的情况下,你最好通过 Ajax 授权请求,这样你就可以 return 某种 jwt 令牌,如果你正在使用它,或者触发任何其他与会话相关的操作在成功登录的前端。

在前端,单击 login 按钮,您可以创建一个名为 login() 的函数,如下所示,并根据从后端收到的响应进行重定向

App.tsx

login() {
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: 'test', password: 'password' })
    };
    fetch('http://localhost:5000', requestOptions)
        .then(response => response.json())
        .then(data => history.push('/someRoute'))
        .catch(err => history.push('/login'));
}

就我而言,我在 nest.js 服务器的后端处理 verifyEmail。

我如何在处理请求后重定向到前端,是使用来自 express 的 res.redirect。


  @Get('verify/:token')
  async verifyUser(@Param('token') token, @Res() response: Response): Promise<any> {
    const redirectUrl = await  this.authService.verifyUserEmail(token);
    response.redirect(redirectUrl);
    return {redirectUrl};
  }

而且,它非常有效。