mongodb 为什么我的navigate钩子在axios里面不工作

wvt8vs2t  于 2023-03-17  发布在  Go
关注(0)|答案(2)|浏览(102)

你好,我是mern stack的新手,这是我在这方面的第一个项目,我在成功登录后通过从后端获取数据导航到下一页时遇到了困难。但即使在将其连接到mongodb数据库并在登录后注册用户的详细信息后,消息也会正确显示,但它不会重定向到下一个预期的页面。同样的情况下,注册页面在注册后也不会进入给定的下一页。
这是我的登录页面:

import React from "react";
import "./Loginform.css";
import "./bg.css";
import axios from "axios";
import { useState } from "react";
import Footer from "./Footer";
import bg from "./Problem.png";
import { useNavigate } from "react-router-dom";
const Loginform=({updateUser})=> {
  const navigate = useNavigate();
  const [ user, setUser] = useState({
    name:"",
    email:"",
    password:""
})

const handleChange = e => {
    const { name, value } = e.target
    setUser({
        ...user,
        [name]: value
    })
}

const login = () => {
    axios.post("http://localhost:5000/loginform", user)
    .then(res => {
        alert(res.data.message)
        updateUser(res.data.user)
        navigate("/new")
    })
}
  return (
    <>
      <div className="gb">
        {/* <span className="sp">WELCOME TO PMS</span> */}
        <div className="bcg">
          {/* <img src={bg} alt="background" /> */}
        </div>
        <p className="p1">
          Login
          <br />
        </p>
        <form action="">
          <div className="container">
            <label className="la">NAME: </label>
            <input
              className="ip"
              type="text"
              placeholder="Enter NAME"
              name="name"
              value={user.name}
              onChange={handleChange}
              required
            />
            <br />
            <label className="la" htmlFor="email">
              Email:{" "}
            </label>
            <input
              className="ip"
              type="email"
              name="email"
              placeholder="Enter Email Id"
              id="email"
              value={user.email}
              onChange={handleChange}
              required
            />
            <br />
            <label className="la" htmlFor="password">
              Password:{" "}
            </label>
            <input
              className="ip"
              type="password"
              name="password"
              placeholder="Enter Password"
              id="password"
              value={user.password}
              onChange={handleChange}
              required
            />
            <br />
            <a style={{ fontSize: "25px",fontFamily:"bold", color:"rgb(25, 25, 112)" }} href="/forgot">
              Forgot Password??
            </a>
            <br />
            <button onClick={login} className="but" type="submit">
              Login
            </button>
            <br />
            <a
              style={{ fontSize: "25px",fontFamily:"bold", color: "black" }}
              href="/registerform"
            >
              New User. Register here??
            </a>
            <br />
          </div>
        </form>
        <Footer />
      </div>
      
    </>
  );
}

export default Loginform;

这是我的App.js:

import React from "react";
import "./App.css";
import Header from "./components1/Header";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import { useState } from "react";
import { useEffect } from "react";
import Home from "./components1/Home";
import Contactus from "./components1/Contactus";
import Loginform from "./components1/Loginform";
import Admin from "./components3/Admin";
import Newproblem3 from "./components3/Newproblem3";
import Completed from "./components3/Completed";
import Pending from "./components3/Pending";
import Rejected from "./components3/Rejected";
import Taskmanager from "./components2/Taskmanager";
import NewProblemtm from "./components2/NewProblemtm";
import Pendingtm from "./components2/Pendingtm";
import Completedtm from "./components2/Completedtm";
import Checkstatus from "./components1/Checkstatus";
import Newproblem from "./components1/Newproblem";
import Solved from "./components1/Solved";
import Registerform from "./components1/Registerform";
import Forgot from "./components1/Forgot";
import New from "./components1/New";
function App() {
  const [ user, setLoginUser] = useState({})
  useEffect(() => {
    setLoginUser(JSON.parse(localStorage.getItem("MyUser")))
  }, [])

  const updateUser = (user) => {
    localStorage.setItem("MyUser", JSON.stringify(user))
    setLoginUser(user)
  }
  return (
    <>
      <Router>
        <div
          style={{
            backgroundImage: "url(/GAT1.jpg)",
            backgroundRepeat: "no-repeat",
            backgroundSize: "100% 185px",
          }}
        >
          <div>
            <Header />
          </div>
        </div>
        <div>
          <Routes>
          <Route path="/home" element=
            {
              user && user._id ?  <Home updateUser={updateUser} /> : <Loginform updateUser={updateUser}/>
            }
            />
            {/* <Route path="/home" element={<Home />} /> */}
            <Route path="/new" element={<New />} />
            <Route path="/loginform" updateUser={updateUser} element={<Loginform />} />
            <Route path="/contactus" element={<Contactus />} />
            <Route path="/newproblem" element={<Newproblem />} />
            <Route path="/checkstatus" element={<Checkstatus />} />
            <Route path="/solved" element={<Solved />} />
            <Route path="/registerform" element={<Registerform />} />
            <Route path="/forgot" element={<Forgot />} />
            <Route path="/admin/*" element={<Admin />} />
            <Route path="/taskmanager" element={<Taskmanager />} />
            <Route path="/newproblem3" element={<Newproblem3 />} />
            <Route path="/completed" element={<Completed />} />
            <Route path="/pending" element={<Pending />} />
            <Route path="/rejected" element={<Rejected />} />
            <Route path="/newproblemtm" element={<NewProblemtm />} />
            <Route path="/pendingtm" element={<Pendingtm />} />
            <Route path="/completedtm" element={<Completedtm />} />
          </Routes>
        </div>
      </Router>
    </>
  );
}

export default App;

这是我的服务器.js:

import express from "express"
import cors from "cors"
import mongoose from "mongoose"

const app = express()
app.use(express.json())
app.use(express.urlencoded())
app.use(cors())

mongoose.connect("mongodb+srv://chetan:1005@cluster0.omoeip5.mongodb.net/?retryWrites=true&w=majority", {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, () => {
    console.log("DB connected")
})

const userSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
})

const User = new mongoose.model("User", userSchema)

//Routes
app.post("/loginform", (req, res)=> {
    const { email, password} = req.body
    User.findOne({ email: email}, (err, user) => {
        if(user){
            if(password === user.password ) {
                res.send({message: "Login Successfull", user: user})
            } else {
                res.send({ message: "Password didn't match"})
            }
        } else {
            res.send({message: "User not registered"})
        }
    })
}) 

app.post("/registerform", (req, res)=> {
    const { name, email, password} = req.body
    User.findOne({email: email}, (err, user) => {
        if(user){
            res.send({message: "User already registerd"})
        } else {
            const user = new User({
                name,
                email,
                password
            })
            user.save(err => {
                if(err) {
                    res.send(err)
                } else {
                    res.send( { message: "Successfully Registered, Please login now." })
                }
            })
        }
    })
    
}) 

app.listen(5000,() => {
    console.log("BE started at port 5000")
})

这是控制台显示的内容:enter image description here

0ve6wy6x

0ve6wy6x1#

让它像

const login = async () => {
    var response = await axios({
        method: 'POST',
        url: 'http://localhost:5000/loginform',
        data: user,
    });

    if (response.data.status) {
        alert(res.data.message)
        updateUser(res.data.user)
        navigate("/new")

    }
}

如果不行就告诉我

5f0d552i

5f0d552i2#

制造

const navigate = useNavigate();

Loginform之外,并添加.catch,以便在请求失败时能够捕获任何错误。

axios.post("http://localhost:5000/loginform", user)
.then(res => {
   alert(res.data.message)
   updateUser(res.data.user)
   navigate("/new")
  })
.catch((error) => { console.log(error)})

相关问题