为什么我的res.status在控制台记录时什么都没有显示?

carvr3hs  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(416)

我正在尝试使用passport js检查登录表单,我希望在状态正确时登录用户,但在状态不正确时返回登录页面。我试着用if-else语句来做这件事,但它不起作用,因为我试着用控制台记录状态,但它什么也没有显示。
这是我的前端:

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)
          return history.push("/home")
        }
        else if(res.status === 400) {
          return 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
dbf7pr2w

dbf7pr2w1#

到达之前 console 您正在返回中的控件
if else 条件移动你的 console.log 之前
if else .

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

相关问题