1

I'm encountering an issue with my Express application where data fetched by a service function is bypassing the middleware and going directly to the client (Postman). Here is my setup:

I have a middleware function fetchCoursesWithSearchKey that handles incoming requests, like so:

async function fetchCoursesWithSearchKey(req, res, next) {
  const searchQuery = req.body;
  let courses = null;

  try {
    courses = await _fetchCoursesBySearchKey(searchQuery);
  } catch (error) {
    logger.error('Failed to fetch golf courses');
    return next(error);
  }

  res.json(courses);
}

And the service function _fetchCoursesBySearchKey responsible for fetching data:

 _fetchCoursesBySearchKey: async ({ searchString, category }) => {
    const keywords = searchString.split(/[\s,]+/);
    const regexPattern = keywords.map((word) => `(?=.*${word})`).join('');
    const regex = new RegExp(regexPattern, 'i');
    try {
      const query = { [category]: regex };
      return await Course.find(query);
    } catch {
      throw Boom.notFound('Failed to fetch the requested golf courses');
    }
  },

The issue arises when making requests via Postman: instead of fetchCoursesWithSearchKey receiving the fetched data from _fetchCoursesBySearchKey, the data seems to be going directly to Postman, leading to errors like ERR_HTTP_HEADERS_SENT.

Additional Context: This behavior occurs specifically when using the JavaScript debug terminal but not when using ZSH. In the debug terminal, the return from _fetchCoursesBySearchKey is going to the client, and the control is returned to the middleware where it's executing res.json(...) resulting in ERR_HTTP_HEADERS_SENT error as shown below.

node:_http_outgoing:703
    throw new ERR_HTTP_HEADERS_SENT('set');
          ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:703:11)
    at ServerResponse.header (/Users/umakanth/Documents/Speed Score/backend/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/Users/umakanth/Documents/Speed Score/backend/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/Users/umakanth/Documents/Speed Score/backend/node_modules/express/lib/response.js:278:15)
    at fetchCoursesWithSearchKey (/Users/umakanth/Documents/Speed Score/backend/src/controller/course.controller.js:80:7)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

Node.js v21.5.0

I was wondering why this is happening only on debug mode. Will be grateful if someone could provide insights on this. Thank you.

Let me know if any additional information is required from my side.

0

Browse other questions tagged or ask your own question.