【问题标题】:why is my res.status showing nothing when I console log it?为什么控制台记录时我的 res.status 什么也没显示?
【发布时间】:2021-10-01 17:14:12
【问题描述】:

我正在尝试使用护照 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

【问题讨论】:

  • 它什么也没有显示,因为您在 console.log 之前有两个 return 语句,因此它会提前返回并且永远不会到达该行。

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


【解决方案1】:

在到达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")
      }
      })
    }

【讨论】:

    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    相关资源
    最近更新 更多