【问题标题】:I'm getting an error status of 400 in server side but getting a 200 status in client side我在服务器端收到 400 错误状态,但在客户端收到 200 状态
【发布时间】:2021-10-01 17:45:59
【问题描述】:

我正在尝试构建登录身份验证,当用户输入正确时,它应该转到主页,但如果没有,它应该将他发送到登录页面。我通过检查 200 和 400 的状态来做到这一点。当我输入错误的用户名时,服务器端确实返回了 400 的代码。但服务器端没有,即使用户是,它仍然会将我重定向到主页不正确。为什么会这样?

import React, {useState} from 'react'
import './login.css'
import axios from 'axios'
import { useHistory } from "react-router-dom";


function Login() {
    const [username, setUsername] = useState("")
    const [password, setPassword] = useState("")
    const [data, setData] = useState(null)

    const history = useHistory()


    const onChangeUsername = (e) => {
      setUsername(e.target.value)
    }

    const onChangePassword = (e) => {
      setPassword(e.target.value)
    }

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

      const users = {
        username: username,
        password: password
      }
      axios.post('http://localhost:4000/users/login', users)
      .then(res => console.log(res.data))
    }

    const loginUser = () => {
      axios.get("http://localhost:4000/users/login", {
        withCredentials: true
      }).then(res => {
        if(res.status === 200) {
          setData(res)
          console.log(res.status)
          history.push("/home")
        }
        else if(res.status === 400) {
          history.push("/login")
      }
          console.log(res.status)
      })
    }

    return (
        <div>
          <img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-logo-vector-png-clipart-1.png" className="twitterlogo____image"/>
          <h1 className="login_____headertext">Log in to Twitter</h1>
          <div className="placeholder_____global">
          <form onSubmit={onSubmit}>
            <input className="placeholder____div" placeholder="Phone, email or username" onChange={onChangeUsername}/>
            <div>
              <input className="placeholder____div" placeholder="Password" type="password" onChange={onChangePassword}/>
            </div>
            <div>
              <button className="twitter___loginbuttonpage" onClick={loginUser}>Log in</button>
            </div>
            </form>
            <div className="forgetPassword_____div">
              <p>Forgot password?</p>
              <p>·</p>
              <p>Sign up for Twitter</p>
            </div>
          </div>
        </div>
    )
}

export default Login

服务器端:

const express = require('express');
const router = express.Router();

const Users = require('../models/users.model.js')
const passport = require("passport")

require('../authentication/passportConfig.js')(passport)


router.route('/').get((req, res) => {
  Users.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json('Error:' + err))
})


router.route('/login').post((req, res, next) => {
  passport.authenticate("local" , (err, user, info) => {
    if (err) throw err;
    if (!user) res.status(400).send("No user exists");
    else {
      req.logIn(user, err => {
        if (err) throw error;
        res.status(200).send("Succesfully Authenticated")
      })
    }
  })(req, res, next)
})

router.route('/login').get((req, res) => {
  res.send(req.user)
})

router.route('/add').post(async(req,res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10)
  const username = req.body.username
  const password = hashedPassword
  const email = req.body.email
  const phone = req.body.phone
  const monthOfBirth = req.body.monthOfBirth
  const dayOfBirth = req.body.dayOfBirth
  const yearOfBirth = req.body.yearOfBirth

  const newUsers = new Users({
    username,
    password,
    email,
    phone,
    monthOfBirth,
    dayOfBirth,
    yearOfBirth
  })

  newUsers.save()
  .then (() => res.json("User Added"))
  .catch(err => res.status(400).json('error' + err))
})



module.exports = router

【问题讨论】:

    标签: node.js reactjs mongodb express passport.js


    【解决方案1】:

    我觉得你把事情搞混了... 出于同一目的,您有两种不同的方法。如果在表单中使用onSubmit,则不需要在按钮中使用onClick

    您应该完全删除loginUser 函数并将逻辑移至onSubmit 方法,如下所示

        const onSubmit = (e) => {
          e.preventDefault()
    
          const users = {
            username: username,
            password: password
          }
          axios.post('http://localhost:4000/users/login', users)
          .then(res => {
            if(res.status === 200) {
              setData(res)
              console.log(res.status)
              history.push("/home")
            }
            else if(res.status === 400) {
              history.push("/login")
          }
              console.log(res.status)
          })
        }
        }
    

    您也可以从按钮中删除onClick 处理程序,并将按钮类型设置为提交如下

       <div>
           <button className="twitter___loginbuttonpage" type="submit">Log in</button>
       </div>
    

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2019-11-04
      • 2018-11-26
      相关资源
      最近更新 更多