表单发布请求后在React中显示JSON表单验证错误数据

时间:2019-03-25 15:29:34

标签: reactjs express axios

我在React中编写的表单发送了一个帖子数据并表达了以下内容的检查:

  1. 如果任何字段留空。
  2. 如果密码> = 8。
  3. 如果密码匹配。
  4. 我的用户还不存在。

如果其中任何一个条件不满足,它将使用res.json发送回一条错误消息。

我的问题是,如何在React with Axios中正确显示它。

P.S。我已经尝试过使用生命周期方法

反应:

import React, { Component } from 'react'
import axios from 'axios'

export default class Register extends Component {
  constructor(){
    super();
    this.state = {
      data: {}
    }
  }
  componentDidMount(){
    axios.post('/register')
         .then(data => console.log(data))
         .catch(err => console.log(err));
  }
  render() {
    return (
      <div>
        <form method = "POST">
          <div>Enter Your name: </div>
          <input id = "name" type = "name" name = "name" />
          <div>Enter Your Email</div>
          <input id = "email" type = "email" name = "email" />
          <div>Enter UserID</div>
          <input id = "userID" type = "userID" name = "userID" />
          <div>Enter your PassWord: </div>
          <input id = "password" type = "password" name = "password" />
          <div>Enter your PassWord Again: </div>
          <input id = "password2" type = "password2" name = "password2" />
          <div>
            <button type = "submit">Submit</button>
          </div>
        </form>
      </div>
    )
  }
}

快递:

const express                 = require('express');
const route                   = express.Router();
const bcrypt                  = require('bcryptjs');
const User                    = require('../models/User');

//Register Route
route.post('/' , (req , res) => {
    //Destructuring data from the request
    const { name , password , password2 , email , userID } = req.body;
    let err = [];

    //If any field was left empty
    if(!name || !password || !password2 || !email || !userID){
        JSON.stringify(err.push("Please Fill In All The Fields."));
        res.json({
            err: err[0]
        });
    }

    //Checking If Passwords Match
    if(password !== password2){
        JSON.stringify(err.push("Passwords Dont Match."));
        res.json({
            err: err[0]
        })
    }

    //Checking Password Length
    if(password.length <= 8){
        JSON.stringify(err.push("Password Must Be Atleast 8 Characters Long."))
        res.json({
            err: err[0]
        })
    }
    //If User Already Exists
    User.findOne({userID: userID})
            .then(user => {
                if(user){
                    JSON.stringify(err.push("Choose A Different Username"))
                    res.json({
                        err: err[0]
                    })
                } else {
                    //If User Does Not Exist
                    const NewUser = new User({
                        name,
                        email,
                        userID,
                        password
                    })
                    //Hashing The Password
                    bcrypt.genSalt(10 , (err , salt) =>{
                        bcrypt.hash(NewUser.password , salt , (err , hash) => {

                            if(err) throw err;
                            NewUser.password = hash;
                            NewUser.save()
                                   .then(() => {
                                       //res.redirect('/login');
                                       res.json({ msg: "New User Saved" });
                                   })
                                   .catch(err => res.json({err: err}));
                        });
                    })
                }
            })
        .catch(err => res.json({err: err}) );
})

module.exports = route;

1 个答案:

答案 0 :(得分:0)

您只需使用.catch(err => this.setState({ err }))

将其传递到状态

然后,您可以在render方法内直接访问它,以在出现以下错误时呈现错误消息:

render() {
  return (
    <div>
      //your component
      {state.err && <span>{err.message}</span>}
    </div>
  );
}