Resetting password with react js (Showing error: Failed to load resources , the server responded with status of 400)

Viewed 41
   import {  useState } from 'react';
   import { useSearchParams } from 'react-router-dom';
   import api from '../contexts/BaseUrl';

function ResetPassword(){
const [searchParams] = useSearchParams();
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [success, setSuccess] = useState(null);

const [err, setErrMsg] = useState("")

const email = searchParams.get('email');
const token = searchParams.get('token');


const handleSubmit = async (e) => {
    e.preventDefault();
    try{
        const response = await api.post(
            '/api/accounts/reset-password', 
            JSON.stringify({password, confirmPassword, email, token}),
            {
                headers:{
                    "Accept" : "application/json",
                    "Content-Type" : "application/json",
                }
            });
     
        setPassword("");
        setConfirmPassword("");
        setSuccess(true);
    }catch(err){          
        setPassword("");
        setConfirmPassword("");
        setSuccess(false);
        if(!err?.response){
            setErrMsg('No Server Response')
        }else{
            setErrMsg('Failed changing password!');
        }
    }
    
}

return (  
     <div>
         <div>Email : {email}</div>
         <button onClick={() => console.log(tokenGet)}>Token</button>
         
                <form className="userContent2" 
                    onSubmit={handleSubmit}
                >
                

                <label>New Password: </label>
                <input
                    type="password"
                    pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
                    value = {password}
                    required
                    onChange={event => {
                        setPassword(event.target.value);
                     
                        if (event.target?.validity?.patternMismatch) {
                            event.target?.setCustomValidity('Min - 8 chars,1 Uppercase, 1 Lowercase, 1 number, 1 special character ');
                        } else {
                            event.target?.setCustomValidity('');
                        }
                    }}
                />
                <label>Confirm New Password: </label>
                <input
                    type="password"
                    pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
                    value = {confirmPassword}
                    required
                    onChange={event => {
                        setConfirmPassword(event.target.value);
                       
                        if (event.target?.value !== password) {
                            event.target?.setCustomValidity('Password doesn\'t match');
                        } else {
                            event.target?.setCustomValidity('');
                        }
                    }}
                />
                <button className='userButton'>Save</button>

                {!success && <div className='error'>{err}</div>}
                {success && <div className='success'>Password Successfully Changed!</div>}
            </form>
        
    </div>
    
 );}


 export default ResetPassword;

I am aware I am making mistake on the client side. Here is the console error:

Failed to load resource: the server responded with a status of 400 (Bad Request)

Here a user give the email, then an email has been sent to the user with a link to reset password. that resetting link has a token and user's email. Using that token and email I pass it to my post request. What am I missing?

1 Answers

The problem I guess with the JSON.stringify

JSON.stringify({password, confirmPassword, email, token})

If you are already using Axios, don't stringify anything. Axios does the job for you. Send all these values as a single javascript object.

Example:

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

For more: Axios Documnetation

Related