【问题标题】:How to consume data from an Express route to a React Router route如何使用从 Express 路由到 React Router 路由的数据
【发布时间】:2020-07-02 02:19:52
【问题描述】:

我有一条在 nodemailer 向用户发送确认电子邮件后命中的快速路由。

router.route('/confirmation/:token').get((req, res, next) => {
  try {
    Token.findOne({ token: req.params.token }, function(err, token) {
      if (err)
        return res.status(404).send({
          type: 'not-verified',
          msg: 'We were unable to find a valid token. Your token my have expired.'
        });
      // If we found a token, find a matching user
      User.findOne({ _id: token._userId, email: req.body.username }, function(err, user) {
        if (err)
          return res
            .status(404)
            .send({ msg: 'We were unable to find a user for this token.' });
        if (user.isVerified)
          return res.status(400).send({
            type: 'already-verified',
            msg: 'This user has already been verified.'
          });

        // Verify and save the user
        user.isVerified = true;
        user.save(function(err) {
          if (err) {
            return res.status(500).send({ msg: err.message });
          }
          return res
            .status(200)
            .send({
              msg: [
                'The account has been verified. Please log in.',
                { userVerified: user.isVerified }
              ]
            })
            .redirect('/login');
        });
      });
    });
  } catch (err) {
    return next(err);
  }
});

电子邮件:

您好,请点击以下链接验证您的帐户: http://localhost:8016/users/confirmation/a217ba992e977079eeeca541677fedcb

自然而然地,我会去:http://localhost:8016/users/confirmation/a217ba992e977079eeeca541677fedcb

并得到响应:

{
  "msg": [
  "The account has been verified. Please log in.",
  {
   "userVerified": true
  }
 ]
}

但我想要的是通过 React 路由器使用这些数据。使用它来制作模态或其他组件。基本上是获取这些数据来为我在客户端上的路线提供动力。

类似:

function PrivateRoute({ children, ...rest }) {
  return (
    <Route
      {...rest}
      render={({ location, props }) =>
        isLoggedIn ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: '/',
              state: { from: location }
            }}
          />
        )
      }
    />
  );
}

  <PrivateRoute path={`/users/confirmation/${params.token}`}>
    {
      <Modal
        isAlertModal={false}
        history={history}
        affirmativeUsed="Yes"
        message="You have now completed your registration!"
        modalActive={true}
      />
    }
  </PrivateRoute>

提前致谢!

【问题讨论】:

    标签: reactjs express routes react-router http-status-codes


    【解决方案1】:

    这不是它的工作原理。在您的 React 组件之一中点击 /confirmation 端点,然后将结果存储在 Redux 存储中。然后,将需要访问该令牌的任何 React 组件连接到 Redux 存储。

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 1970-01-01
      • 2018-06-09
      • 2020-11-30
      • 2017-10-07
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      相关资源
      最近更新 更多