Below are the codes for simple login, but even after successful login the navigation is not working. I am unable to resolve this
login.js
import './Login.css'
import { Link, useNavigate } from 'react-router-dom';
import { useState } from 'react';
import axios from 'axios';
function Login() {
const navigate = useNavigate()
const [username, setusername] = useState('');
const [password, setpassword] = useState('');
const handleApi = () => {
console.log({ username, password });
const url = 'http://localhost:4000/login';
const data = { username, password };
axios.post(url, data)
.then((res) => {
console.log(res.data);
if (res.data.message) {
alert(res.data.message);
if (res.data.token) {
localStorage.setItem('token', res.data.token);
navigate('/');
}
}
})
.catch((err) => {
console.log(err);
alert("SERVER ERROR");
})
}
return (
<div>
<div className="container">
<h1>LOGIN</h1>
<form>
<input
type="text"
placeholder="Enter your Email ID"
value={username}
onChange={(e) => {
setusername(e.target.value)
}}
required
/>
<input
type="text"
placeholder="Enter your Password"
value={password}
onChange={(e) => {
setpassword(e.target.value)
}}
required
/>
<button className="btn" onClick={handleApi}>LOGIN</button>
<p>Not Having An Account <Link to="/signup">Signup</Link></p>
</form>
</div>
</div>
)
}
export default Login;
This is my index.js file where route is defined. I am unable to figure out the where the problem is happening.
import './index.css';
import * as React from "react";
import { createRoot } from "react-dom/client";
import {
createBrowserRouter,
RouterProvider
// Route,
// Link,
} from "react-router-dom";
import Home from './components/Home.jsx';
import Login from './components/Login/Login.jsx';
import Signup from './components/Signup/Signup.jsx';
const router = createBrowserRouter([
{
path: "/",
element: <Home />,
},
{
path: "/about",
element: <div>About</div>,
},
{
path: "/login",
element: <Login />,
},
{
path: "/signup",
element: <Signup />,
},
]);
createRoot(document.getElementById("root")).render(
<RouterProvider router={router} />
);
This is my backend code
const express = require('express')
const cors = require('cors')
var jwt = require('jsonwebtoken');
const bodyParser = require('body-parser')
const app = express()
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const port = 4000
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/sparebazar").then(()=>{
console.log("mongoose connected ")
}).catch((e)=>{
console.log("not connected" )
console.log(e)
})
const Users = mongoose.model('Users', { username: String, password: String });
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/signup', (req, res) => {
console.log(req.body);
const username = req.body.username;
const password = req.body.password;
const user = new Users({ username: username, password: password });
user.save()
.then(() => {
res.send({ message: 'saved successfully' })
})
.catch(() => {
res.send({ message: 'server error' })
})
})
app.post('/login', (req, res) => {
// console.log(req.body);
const username = req.body.username;
const password = req.body.password;
Users.findOne({ username: username })
.then((result) => {
// console.log(result, " user data");
if (!result) {
console.log( " user not found");
res.send({ message: 'User Not Found' });
}
else {
if (result.password == password) {
const token = jwt.sign({
data: result
}, 'MYKEY', { expiresIn: 60 });
console.log(result," user data is correct ");
res.send({ message: 'Find successfully', token: token })
}
if (result.password != password) {
console.log(" password data is wrong ");
res.send({ message: 'Password is Wrong' })
}
}
})
.catch(() => {
res.send({ message: 'server error' })
})
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
2
Answers
I think it’s easy to use
useHistory
.I hope this answer can help you.
Issue
Your
Login
component is submitting theform
element and isn’t preventing the default form submission from occurring, which is reloading the page on the current route.button
elements aretype="submit"
by default, so this is why the form is submitted.Solutions
Specify that the "LOGIN" button is a
type="button"
explicitly, so when clicked it doesn’t submit the form.Specify that the "LOGIN" button is a
type="submit"
explicitly, and move thehandleApo
callback to theform
element’sonSubmit
handler and prevent the default form action.While the first is the easier fix, it doesn’t prevent the submission of the
form
element completely. For this reason the second solution would/should be the more correct fix.