Ошибка: невозможно установить заголовки после их отправки. NodeJS используется асин c функция - PullRequest
0 голосов
/ 11 января 2020

Я столкнулся с небольшой проблемой, которая блокирует меня. Я работаю над сервисом аутентификации пользователей для моего приложения Node.js. Я работаю над маршрутом пользователя PUT и мне нужно сравнить старый и новый пароль, используемый bcrypt.

Смысл добавления сравнительного try/catch Я получаю следующую ошибку:

Ошибка: невозможно установить заголовки после их отправки.

app.put(`/users/:email`, checkAuthenticated, envisionDuplicateEmails, async (req, res) => {
  const accountEmail = req.params.email
  body = req.body
  const user = users.find((user) => user.email === accountEmail)
  const index = users.indexOf(user)

  if (!user) {
    res.status(500).send('Account not found.');
  } else {

    try {
      if (await bcrypt.compare(body.password, user.password)) {
        body.password = user.password
      } else {
        const hashedPassword = await bcrypt.hash(body.password, 10)
        body.password = hashedPassword
      }
    } catch (e) {
      return res.status(500).send('Internal server error');
    }

    const updatedAccount = { ...user, ...body }
    users[index] = updatedAccount
    res.redirect('/')
  }
})

служебные функции:

function checkAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next()
  }
  res.redirect('/login')
}

function envisionDuplicateEmails(req, res, next) {
  accountEmail = req.params.email
  bodyEmail = req.body.email

  if (bodyEmail) {
    if (bodyEmail != accountEmail) {
      checkEmailExist(req, res, next)
    }
  }
  return next()
}

function checkEmailExist(req, res, next) {
  const accountEmail = req.body.email
  const getAccount = users.find((user) => user.email === accountEmail)

  if (getAccount === undefined) {
  } else {
    return res.status(500).send({ 'message': 'Account email already exist' })
  }
  return next()
}

Спасибо за помощь: P

1 Ответ

1 голос
/ 11 января 2020

Вы пытаетесь повторно выполнить res.status(500) дважды.

В предложении try / catch просто добавьте ключевое слово return, например:

try {
    if (await bcrypt.compare(body.password, user.password)) {
      body.password = user.password
    } else {
      const hashedPassword = await bcrypt.hash(body.password, 10)
      body.password = hashedPassword
    }
  } catch (e) {
    // I've added the return keyword here
    return res.status(500).send('Internal server error');
  }

Теперь, когда ваш try / catch отлавливает ошибку, код не продолжается и останавливается здесь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...