skip to Main Content

I am getting above error when i am fetching the data from axios , when all the validations are correct, i get the data , but when i try to send wrong data it gives me above error

import React from 'react'
import { TextField, Button } from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import GoogleIcon from '@mui/icons-material/Google';
import FacebookIcon from '@mui/icons-material/Facebook';
import { Link } from "react-router-dom";
import "../styles/home.css"
import useInputState from "../hooks/useInputState"
import axios from 'axios';

function Login() {

    const [username, updateUsername, resetUsername] = useInputState("")
    const [password, updatePassword, resetPassword] = useInputState("")
    const HOST = "http://localhost:8080"

    const handleSubmit = async (evt) => {
        evt.preventDefault()
        const config = { headers: { 'Content-Type': 'application/json' } }
        const data = JSON.stringify({ username, password })
        console.log(data)
        const response = await axios.post(`${HOST}/api/auth/login`, data, config)
        console.log(response.data)
        resetUsername()
        resetPassword()
        // if (resp.data.success) {
        //     console.log("redirecting to oppp")
        // } else {
        //     alert("invalid credentials")
        // }
    }

    return (
        <div>
            <div className="container mt-5 addnotes" >
                <Button className="mb-4" variant="text" color="secondary" startIcon={<ArrowBackIcon />} component={Link} to="/" style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif" }}>Home</Button>
                <h2 style={{ fontWeight: "Bold" }}>Login</h2>
                <p className="mb-4">Sign in on the internal platform</p>
                <div className="d-flex">
                    <Button size="large" fullWidth className="mb-4 me-4" variant="contained" color="primary" startIcon={<FacebookIcon />} component={Link} to="/" style={{ textTransform: "none", fontSize: "1.1rem", color: "White", fontFamily: "'Poppins', sans-serif" }}>Login with Facebook</Button>
                    <Button size="large" fullWidth className="mb-4" variant="contained" color="error" startIcon={<GoogleIcon />} component={Link} to="/" style={{ textTransform: "none", fontSize: "1.1rem", color: "White", fontFamily: "'Poppins', sans-serif" }}>Login with Google</Button>
                </div>
                <p className="mb-4 d-flex justify-content-center">or login with username and password</p>
                <form onSubmit={handleSubmit}>
                    <div className="mb-4">
                        <TextField value={username} onChange={updateUsername} inputProps={{ minLength: 1 }} color="secondary" label="Username" variant="outlined" fullWidth required style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }} />
                    </div>
                    <div className="mb-4">
                        <TextField type="password" value={password} onChange={updatePassword} inputProps={{ minLength: 1 }} color="secondary" label="Password" variant="outlined" fullWidth required style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }} />
                    </div>
                    <Button disabled={username.length < 1 || password.length < 1} type="submit" fullWidth size="large" className="mb-4" variant="contained" color="secondary" style={{ textTransform: "none", fontFamily: "'Poppins', sans-serif", fontSize: "1.1rem" }}>Add Note</Button>
                </form>
                <p>Don't have an account? <Link to="/register" >register</Link> </p>
            </div>
        </div>
    )
}

export default Login

The error is occured in handlesubmit function when i try to give wrong input which should give me a response with an error but it gives me following error and the usernamereset and passwordReset does not get executed , but when i give correct username and password i get the correct data

Error:

Uncaught (in promise) Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.onloadend (xhr.js:66)

Backend Code for that route:

router.post('/login', validateUserLogin, catchAsync(loginUser))
module.exports.loginUser = async (req, res) => {
    const { username, password } = req.body
    const foundUser = await User.findAndValidate(username, password)
    if (foundUser) {
        const data = {
            user: { id: foundUser._id }
        }
        const authToken = jwt.sign(data, process.env.JWT_KEY)
        res.send({ success: true, authToken })
    } else {
        return res.status(400).json({ success: false, err: { user: foundUser }, message: "invalid credentials !!" })
    }
}

when i am sending wrong password an username i am not getting this invalid credentials message

2

Answers


  1. TL:DR: You’re doing everything right

    I suppose on the back end side, there is a handler which will check if your request is correct, and if it’s not , will send you 400 code

    More on 400 error

    Login or Signup to reply.
  2. You are not handling error in handlesubmit

    While using promises, either use try-catch if you are using await, or use then and catch to properly handler promise rejections.

    In your code, axios will reject the promise in case of http code 400 and you are not handling that error anywhere, so any code after await axios.post(${HOST}/api/auth/login, data, config); won’t run.

    Use try-catch to properly handle that error.

    handleSubmit = async (evt) => {
            evt.preventDefault();
            try {
                const config = { headers: { "Content-Type": "application/json" } };
                const data = JSON.stringify({ username, password });
                console.log(data);
                const response = await axios.post(`${HOST}/api/auth/login`, data, config);
                console.log(response.data);
                resetUsername();
                resetPassword();
            } catch (err) {
                // do something when error occurrs
                console.log(err);
            }
        };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search