0.chunk.js:610 POST http://localhost:3000/api/users/register 400错误请求

问题描述

我正在制作一个具有注册登录功能的 MERN 应用程序。当我尝试在浏览器中提交表单时,控制台会向我显示 400 个错误的请求。该功能适用​​于后端并返回 200 ok 状态,但不适用于前端。

dispatchXhrRequest  @   0.chunk.js:610
xhrAdapter  @   0.chunk.js:455
dispatchRequest @   0.chunk.js:1079
Promise.then (async)        
request @   0.chunk.js:866
Axios.<computed>    @   0.chunk.js:891
wrap    @   0.chunk.js:1421
(anonymous) @   main.chunk.js:445
(anonymous) @   0.chunk.js:44123
(anonymous) @   0.chunk.js:44631
Register.onSubmit   @   main.chunk.js:1073
callCallback    @   0.chunk.js:12247
invokeGuardedCallbackDev    @   0.chunk.js:12296
invokeGuardedCallback   @   0.chunk.js:12356
invokeGuardedCallbackAndCatchFirstError @   0.chunk.js:12371
executedispatch @   0.chunk.js:16606
processdispatchQueueItemsInorder    @   0.chunk.js:16638
processdispatchQueue    @   0.chunk.js:16651
dispatchEventsForPlugins    @   0.chunk.js:16662
(anonymous) @   0.chunk.js:16873
batchedEventUpdates$1   @   0.chunk.js:30558
batchedEventUpdates @   0.chunk.js:12045
dispatchEventForPluginEventSystem   @   0.chunk.js:16872
attemptTodispatchEvent  @   0.chunk.js:14355
dispatchEvent   @   0.chunk.js:14273
unstable_runWithPriority    @   0.chunk.js:45915
runWithPriority$1   @   0.chunk.js:19653
discreteUpdates$1   @   0.chunk.js:30575
discreteUpdates @   0.chunk.js:12057
dispatchdiscreteEvent   @   0.chunk.js:14239

这是我的注册功能的控制器代码

const express = require("express");

const router = express.Router();

const bcrypt = require("bcryptjs");

const jwt = require ("jsonwebtoken");

const keys = require("../../config/key");


const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");


const User = require("../../models/User");


router.post("/register",(req,res) => {



//FORM VALIDATION

const {errors,isValid } = validateRegisterInput(req.body)


//CHECK VALIDATION

if(!isValid) {
    return res.status(400).json(errors)
}

User.findOne({ email: req.body.email }).then( returnedUser => {
    
    if(returnedUser) {
        return res.send(400).json({email: "Email already exists"});
    }
});


// saving user with request information to database
const newUser = new User({
    name: req.body.name,email: req.body.email,password: req.body.password,});

bcrypt.genSalt(10,(err,salt)=>{
    bcrypt.hash(newUser.password,salt,hash)=>{
        if(err) throw err;
        newUser.password = hash;

        newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
    });

});

这是我的 userSchema 模型

const UserSchema = new Schema({
    name: {
      type: String,required: true
    },email: {
      type: String,password: {
      type: String,date: {
      type: Date,default: Date.Now
    }
  });


// const UserSchema = new Schema({
//     name: {type: String,required: true},//     email: {type: String,//     password: {type: String,//     date: {type: Date,default: Date.Now},//     // classwork: [classworkSchema],//     // outcomes: [OutcomesSchema],//     // meetups: [MeetupSchema],// })

module.exports= User = mongoose.model("users",UserSchema);

这是我的寄存器组件。


import React,{ Component } from "react";
import { Link,withRouter } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { registerUser } from "../../actions/authActions";
import classnames from "classnames";

class Register extends Component {
  constructor() {
    super();
    this.state = {
      name: "",email: "",password: "",password2: "",errors: {},};
  }

  componentDidMount() {
    // If logged in and user navigates to Register page,should redirect them to dashboard
    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.id]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

      const newUser = {
        name: this.state.name,email: this.state.email,password: this.state.password,password2: this.state.password2,};

    console.log(newUser);
    this.props.registerUser(newUser,this.props.history);
  };
  render() {
    const { errors } = this.state;
    return (
      <div className="container">
        <div className="row">
          <div className="col s8 offset-s2">
            <Link to="/" className="btn-flat waves-effect">
              <i className="material-icons left">keyboard_backspace</i> Back to
              home
            </Link>
            <div className="col s12" style={{ paddingLeft: "11.250px" }}>
              <h4>
                <b>Register</b> below
              </h4>
              <p className="grey-text text-darken-1">
                Already have an account? <Link to="/login">Log in</Link>
              </p>
            </div>
            <form novalidate onSubmit={this.onSubmit}>
              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.name}
                  error={errors.name}
                  id="name"
                  type="text"
                  className={classnames("",{
                    invalid: errors.name
                  })}
                />
                <label htmlFor="name">Name</label>
                <span className="red-text">{errors.name}</span>
              </div>
              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.email}
                  error={errors.email}
                  id="email"
                  type="email"
                  className={classnames("",{
                    invalid: errors.email
                  })}
                />
                <label htmlFor="email">Email</label>
                <span className="red-text">{errors.email}</span>
              </div>
              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.password}
                  error={errors.password}
                  id="password"
                  type="password"
                  className={classnames("",{
                    invalid: errors.password
                  })}
                />
                <label htmlFor="password">Password</label>
                <span className="red-text">{errors.password}</span>
              </div>
              <div className="input-field col s12">
                <input
                  onChange={this.onChange}
                  value={this.state.password2}
                  error={errors.password2}
                  id="password2"
                  type="password"
                  className={classnames("",{
                    invalid: errors.password2
                  })}
                />
                <label htmlFor="password2">Confirm Password</label>
                <span className="red-text">{errors.password2}</span>
              </div>
              <div className="col s12" style={{ paddingLeft: "11.250px" }}>
                <button
                  style={{
                    width: "150px",borderRadius: "3px",letterSpacing: "1.5px",marginTop: "1rem",}}
                  type="submit"
                  className="btn btn-large waves-effect waves-light hoverable blue accent-3"
                >
                  Sign up
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

Register.propTypes = {
  registerUser: PropTypes.func.isrequired,auth: PropTypes.object.isrequired,errors: PropTypes.object.isrequired,};

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

export default connect(mapStatetoProps,{ registerUser })(withRouter(Register));

这里是操作

import axios from "axios";
import setAuthToken from "../utils/setAuthToken";
import jwt_decode from "jwt-decode";
import {
  GET_ERRORS,SET_CURRENT_USER,USER_LOADING
} from "./types";


// Register User


export const registerUser = (userData,history) => dispatch => {
  axios
    .post("/api/users/register",userData)
    .then(res => history.push("/login")) // re-direct to login on successful register
    .catch(err =>
      dispatch({
        type: GET_ERRORS,payload: err.response.data
      })
    );
};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)