E
E
EmKotlety2021-09-11 08:03:49
Express.js
EmKotlety, 2021-09-11 08:03:49

Why doesn't redirect work in express?

throws an error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Here is the route:

router.post('/restore',
    [check('email', 'некорректный email').normalizeEmail().isEmail(),
    check('login', 'некорректный login').not().isEmpty().trim().escape()],  
    async(req, res, next)=> {
        try {
            const errors = validationResult(req)
            if (!errors.isEmpty()) {
                return res.status(400).json({
                    errors: errors.array(),
                    message: "Некорректные данные при регистрации"
                })
            }
            const {login, email } = req.body
            const user = await User.findOne({email: email})
            if(!user){
                return next(ApiError.badRequest('Пользователь не найден'))
            }
            if(user.login !== login){
                return next(ApiError.badRequest('Неверный login'))
            }
            let password = uuid.v4()
            
            let upgratepassword =  password.replace(/-/g,'t').slice(0,10)
            const hashedPassword = await bcrypt.hash(upgratepassword, 12)
            console.log(upgratepassword)
            await User.updateOne({ email: email }, {$set:{password: hashedPassword}})
            await mailService.sendRestorePasswordMail(email, upgratepassword )
            return  res.json('новый пароль был отправлен на почту'),////ЧТО-ТО В ЭТИХ СТРОЧКАХ
            res.redirect('http://localhost:3000/restore')////ЧТО-ТО В ЭТИХ СТРОЧКАХ
           
        }catch(e){
            next( ApiError.internal("хмм, вот ведь незадача, что-то пошло не так"))
            console.log(e)
        }
    })

Here is the react request:
export const  restorePassword= (email, login)=>{
    return async dispatch => {
        dispatch(setLoader()) 
        try{
            const response = await axios.post(`http://localhost:5000/api/auth/restore`,
            {email, login})            
                 dispatch(disableLoader());
            
          }
        catch(e){
        dispatch(disableLoader());
        console.log(e)
        }
    }

}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question