У меня мало знаний о полном стеке MERN.Здесь у меня есть маршрут в nodejs, который получает токен от переднего плана реакции, и он просто помечает «isVerified = true» после нахождения нужного пользователя в mongoDb.Но вместо этого я получаю ошибку, которая говорит, что мое обещание отклоняется.Я понятия не имею, что вызвало это.Я приложил код ниже.Пожалуйста, помогите мне через это.
Я пробовал несколько вещей, таких как изменение тела запроса и т. Д. Но у меня ничего не получалось.
Это действие, при котором вызывается маршрут.
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");
});
});