我正在尝试通过令牌确认用户,但显示错误

时间:2019-03-30 04:15:30

标签: node.js reactjs react-redux

我对MERN全栈知识不多。在这里,我在nodejs中有一条路由,该路由从react前端获取令牌,在mongoDb中找到所需的用户后,它简单地标记为“ isVerified = true”。但是相反,我遇到了错误,说我的承诺被拒绝了。我不知道是什么原因造成的。我已经附上了下面的代码。请帮我解决这个问题。

我已经尝试了多种方法,例如更改请求正文等。但是对我没有任何帮助。

这是调用路由的动作。

export const verifyUser = (verifyEmail, token, history) => dispatch => {
  axios
    .post(`/api/users/confirmation/${token}`, verifyEmail)
    .then(res => history.push("/login"))
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

这是我的回复表单,要求输入电子邮件然后进行验证。

import React, { Component } from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import { verifyUser } from "../../actions/authActions";
import TextFieldGroup from "../common/TextFieldGroup";

class Confirmation extends Component {
  constructor() {
    super();
    this.state = {
      email: "",
      errors: {}
    };
    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  componentDidMount() {
    if (this.props.auth.isAuthenticated) {
      this.props.history.push("/dashboard");
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }
  }

  onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }

  onSubmit(e) {
    e.preventDefault();

    const verifyEmail = {
      email: this.state.email
    };

    this.props.verifyUser(verifyEmail, this.props.token, this.props.history);
  }

  render() {
    const { errors } = this.state;
    return (
      <div className="confirmation">
        <div className="container">
          <div className="row">
            <div className="col-md-8 m-auto">
              <h1 className="display-4 text-center">User verification</h1>
              <p className="lead text-center">Enter your email to verify</p>
              <form noValidate onSubmit={this.onSubmit}>
                <TextFieldGroup
                  placeholder="Email"
                  name="email"
                  type="email"
                  value={this.state.email}
                  onChange={this.onChange}
                  error={errors.email}
                />
                <input type="submit" className="btn btn-info btn-block mt-4" />
              </form>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

Confirmation.propTypes = {
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});

export default connect(
  mapStateToProps,
  { verifyUser }
)(withRouter(Confirmation));

这是路由器

router.post("/confirmation/:token", (req, res) => {
  Veri.findOne({ token: req.body.token })
    .then(token => {
      if (!token) {
        errors.email =
          "We were unable to find a valid token. Your token may have expired";
        return res.status(400).json(errors);
      }
      User.findOne({ _id: token._userId, email: req.body.email }).then(user => {
        if (!user) {
          errors.email = "We were unable to find a user for this token";
          return res.status(400).json(errors);
        }
        if (user.isVerified) {
          errors.email = "This user has already been verified";
          return res.status(400).json(errors);
        }
        // Verify and save the user
        user.isVerified = true;
        user.save().then(user => res.json(user));
      });
    })
    .catch(function() {
      console.log("Promise Rejected");
    });
});

1 个答案:

答案 0 :(得分:0)

除非您已设置一些Express中间件,该中间件将查询变量解析为req.body,否则将永远不会读取令牌。 req.body应该是只有一个字段的对象:email。您的查询参数位于req.params对象中。可以肯定的是,承诺Veri.findOne({ token: req.body.token })将传递null到其回调函数或完全拒绝。在任何情况下,它都不具有期望的效果。将第一个查询更改为Veri.findOne({ token: req.params.token })应该可以解决主要问题。

也可能是您的Express应用程序中没有主体解析器中间件的情况。如果没有,req.body将是未定义的,尝试访问其中的字段将导致TypeError。确保您使用正文解析器填充req.body

最后,可能是errors对象是undefined。即使不是,对这样的对象进行突变也被认为是不好的做法。而不是像

errors.email = "... error message"

const errors = { email: "... error message" }

或保持原样并将错误初始化为处理程序顶部的空对象。

router.post("/confirmation/:token", (req, res) => {
  const errors = {}
  ...
})