In my node express application, I have a couple of routes, one is a specific route and a wildcard route (for unmatched routes), below is my routes.
// Routes
app.options('/*', (req, res) => {
// Return CORS headers
res.cors().send({});
});
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocs));
app.use('/', indexRouter);
// handling unmatched routes
app.use((req, res) => {
console.log('CMACMD: ');
return res.send(ErrorHelper({
message: `Cannot find ${req.method} endpoint for ${req.path}`,
statusCode: 404,
}).payload);
});
Ideally what has to happen is, If /
matches then it should not go to the below-unmatched route function. It works perfectly for GET requests in the /
route, but when I make a POST request to /
, it matches both routes, it first executes and sends the response to POST route and then matches the last route. So I receive this ERR_HTTP_HEADERS_SENT
.
What is going on here? why it behaves strangely for POST only? what should I do to make it work?
Stacktrace:
node:internal/process/promises:245
product-list-api | triggerUncaughtException(err, true /* fromPromise */);
product-list-api | ^
product-list-api |
product-list-api | Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
product-list-api | at new NodeError (node:internal/errors:329:5)
product-list-api | at ServerResponse.setHeader (node:_http_outgoing:579:11)
product-list-api | at ServerResponse.header (/app/node_modules/express/lib/response.js:771:10)
product-list-api | at ServerResponse.send (/app/node_modules/express/lib/response.js:170:12)
product-list-api | at ServerResponse.json (/app/node_modules/express/lib/response.js:267:15)
product-list-api | at defaultResolve (/app/src/controller.js:40:24)
product-list-api | at controller (/app/src/controller.js:61:12)
product-list-api | at processTicksAndRejections (node:internal/process/task_queues:94:5)
product-list-api | at async addNewProduct (/app/src/controllers/productsController.js:20:3) {
product-list-api | code: 'ERR_HTTP_HEADERS_SENT'
product-list-api | }