After reviewing numerous discussions on the same topic, I am struggling to identify where I might be sending the headers initially. The stack trace provided indicates the following:
It is concerning that I receive a 204 as it successfully adds to the database, only to encounter a 404 later on. It is evident that an issue exists, although the insight eludes me.
I have attempted to insert returns into every res.json()
statement without success.
OPTIONS /api/users/favorites 204 1.822 ms - 0
PATCH /api/users/favorites 404 19.769 ms - 160
Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:455:11)
at ServerResponse.header (/Users/beers/projects/node/cryptopal-api/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/beers/projects/node/cryptopal-api/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/beers/projects/node/cryptopal-api/node_modules/express/lib/response.js:267:15)
at /Users/beers/projects/node/cryptopal-api/src/users/usersRouter.js:30:38
From previous event:
at Builder.Target.then (/Users/beers/projects/node/cryptopal-api/node_modules/knex/lib/interface.js:27:24)
at /Users/beers/projects/node/cryptopal-api/src/users/usersRouter.js:19:8
at Layer.handle [as handle_request] (/Users/beers/projects/node/cryptopal-api/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/beers/projects/node/cryptopal-api/node_modules/express/lib/router/route.js:137:13)...
Below is the code snippet from my usersRouter.js
:
require('dotenv').config();
const express = require('express');
// const rp = require('request-promise');
const usersRouter = express.Router()
const jsonParser = express.json()
const UsersService = require('./usersService.js')
const { requireAuth } = require('../middleware/jwt-auth.js')
usersRouter
.patch('/favorites', requireAuth, (req,res,next) => {
const db = req.app.get('db');
const { coinID } = req.body;
const { user_id } = req;
console.log(res.headersSent) // EQUALS FALSE
...
module.exports = usersRouter;
The error seems to stem from within the jwt-auth.js
file, even though the execution completes successfully and inserts the favorite into the database upon user authentication before encountering header-related issues.