【问题标题】:How to Redirect From Backend To FrontEnd after Authentication身份验证后如何从后端重定向到前端
【发布时间】:2020-08-14 08:16:40
【问题描述】:

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

【问题讨论】:

    标签: node.js authentication authorization


    【解决方案1】:

    在前端,单击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'));
    }
    

    【讨论】:

      【解决方案2】:
      res.writeHead(302, {
          Location: 'http://front-end.com:8888/some/path'
      });
      res.end();
      

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          在您的情况下,您最好通过 Ajax 对请求进行身份验证,这样您可以在使用它时返回某种 jwt 令牌,或者在成功登录时在前端触发任何其他与会话相关的操作。

          【讨论】:

            【解决方案5】:

            在我的例子中,我在 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};
              }
            

            而且,它就像一个魅力。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-01-20
              • 2019-06-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-12-04
              • 1970-01-01
              相关资源
              最近更新 更多