发布请求:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

时间:2020-11-04 18:59:20

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

我正在制作一个简单的后端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;

1 个答案:

答案 0 :(得分: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。具有回调和提取。因此,同一请求包含多个res.json