簡體   English   中英

使用 react js 重置密碼(顯示錯誤:加載資源失敗,服務器響應狀態為 400)

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

   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;

我知道我在客戶端犯了錯誤。 這是控制台錯誤:

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

此處,用戶提供 email,然后已將 email 發送給用戶,其中包含重置密碼的鏈接。 該重置鏈接具有令牌和用戶的 email。 使用該令牌和 email 我將其傳遞給我的發布請求。 我錯過了什么?

我猜JSON.stringify的問題

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

如果您已經在使用 Axios,請不要對任何內容進行字符串化。 Axios 為您完成這項工作。 將所有這些值作為單個 javascript object 發送

例子:

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

更多信息: Axios 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM