javascriptnode.jsexpressnode-fetch

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


I'm making a simple backend API but I keep getting this error when I try to post:

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

The first part of the code seems to run but I'm not sure why the rest is erroring. I've tried many solutions and they don't seem to work. I think I'm doing something incorrectly. Any help would be appreciated.

Here is my code:

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;

Solution

  • 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
        })
      })
    

    The erreor is because execution goes into bcrypt.has callback AND fetch. So the same request has more than one res.json,