【问题标题】:Post request: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client发布请求:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
【发布时间】:2021-02-17 12:08:06
【问题描述】:

我正在制作一个简单的后端 API,但是当我尝试发布时,我不断收到此错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

代码的第一部分似乎可以运行,但我不确定为什么其余部分会出错。我尝试了很多解决方案,但它们似乎不起作用。我想我做错了什么。任何帮助将不胜感激。

这是我的代码:

import { Router } from 'express';
import bcrypt from 'bcryptjs'
import fetch from 'node-fetch';

const router = Router(),
      A = require('../../models/A');

router.post('/a/:n/:username', (req, res) => {
  bcrypt.genSalt(10, (err, salt) => {
    if (err) return res.json({ message: 'error' })
    bcrypt.hash(req.params.key, salt, (err, hash) => {
      if (err) return res.json({ message: 'error' })
      if (req.params.n !== hash) return res.json({ message: 'no access' });
    })
  })
  fetch(`https://api.mojang.com/users/profiles/minecraft/${req.params.username}`)
    .then(res => res.json())
    .then(json => {
      if (!json) return res.json({ message: 'Invalid user.' });
      A.findOne({ id: json.id }).then((id) => {
        if (id) {
          res.json({ id: id.id });
        } else {
          const a = new A({
            id: json.id,
            created: Date.now()
          })
          a.save()
          res.json({ id: json.id })
        }
      })
    });
})

export default router;

【问题讨论】:

  • 你不认为无论你的 Bcrypt 中的条件是否满足或这里肯定会发生级联效应,代码都会级联

标签: javascript node.js express fetch node-fetch


【解决方案1】:
router.post('/a/:n/:username', (req, res) => {
  bcrypt.genSalt(10, (err, salt) => {
    if (err) return res.json({ message: 'error' })
    bcrypt.hash(req.params.key, salt, (err, hash) => {
      if (err) return res.json({ message: 'error' })
      if (req.params.n !== hash) return res.json({ message: 'no access' });

      //Do the fetch here
    })
  })

错误是因为执行进入 bcrypt.has callback AND fetch。所以同一个请求有不止一个res.json

【讨论】:

  • 我还建议您在 fetch 中添加一个 .catch 以处理错误情况,以使用 return a.save().then( () => res.json({id:json.id}); 以使所有内容都正确使用异步
猜你喜欢
  • 2020-05-26
  • 2018-09-19
  • 2020-09-22
  • 2023-01-19
  • 2021-02-26
  • 2021-08-20
  • 2019-09-28
  • 2019-12-25
相关资源
最近更新 更多