Oops: [ERR_HTTP_HEADERS_SENT]: Headers can't be set once they've been sent to the client, please fetch again

I'm encountering an issue with my code where I am unable to make a fetch request when invoking sendPushMessages(message) due to HTTP ERRORS, but I am unsure of the root cause.

The console is displaying the following error message: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Furthermore, if I comment out the line: res.status(200).send({shop: shop[0]}); the code still does not work.

const {models} = require('../models');
const Sequelize = require('sequelize');

exports.findshop = async (req, res, next) => {

  sendPushMessages = async (message) => {
    try{
      let response = await fetch('https://exp.host/--/api/v2/push/send', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Accept-encoding': 'gzip, deflate',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(message),
      });

      let responseData = await response.json();
      console.log(responseData);
    }
    catch (error) {
      next(error);
    }
  }

  try {
      console.log(req.body.latitud)
      console.log(req.body.longitud)
      const user = req.user;
      const shops = await models.Shop.findAll({
        include:[{ model: models.Product, as: 'placements'}]
      });

      const shop = shops.filter(shp => {
        if (Math.abs(shp.latitud - req.body.latitud) <= 0.001 && Math.abs(shp.longitud - req.body.longitud) <= 0.001){
          return shp;
        }
      });

      if (shop[0] && user) {
        shop[0].placements.forEach(item => {
          if (item.dataValues.isoffer){
            const message = {
                to: user.pushtoken,
                sound: 'default',
                title: 'Big Sale Alert! Don't Miss Out!',
                body: item.productname + ' ' + item.price.toString() + '€',
            };
            sendPushMessages(message);
          }
        })  
        res.status(200).send({shop: shop[0]});
      } else {
        res.status(200).send({shop: null});
      }
  } catch (error) {
      next(error);
  }
};

Answer №1

After reviewing the provided code snippet (it would be beneficial to also see the top-level request handler for a complete understanding of the code flow), it appears that there is a potential issue if an error occurs within the sendPushMessages() function. This error could result in calling the next(err) function and continuing within the outer loop, potentially trying to send another response which leads to the error message related to ERR_HTTP_HEADERS_SENT.

In order to address this issue, error handling should be implemented when invoking the sendPushMessages() function to halt the loop in case of an error. One approach to resolve this would be to remove the catch() block from sendPushMessages() and allow the rejection to propagate back to the caller. Additionally, add an await keyword before the call to sendPushMessages(message) as shown below:

await sendPushMessages(message);

This modification ensures that if sendPushMessages() throws an error, it triggers the catch block within the findshop() function, eventually invoking next(error) once without sending any additional responses.

If your question pertains to the error encountered when accessing

https://exp.host/--/api/v2/push/send'
, it would be helpful to know the specific error message you are facing. To better understand the error, consider adding console.log(error) within the catch() handler to log the exact error. In my experience, logging the precise error at the lowest level is essential for effective debugging.

Answer №2

Here is the error message that popped up:

fetch is not defined POST /location 500 8.371 ms - 32 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:526:11) at ServerResponse.header (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:767:10) at ServerResponse.send (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:170:12) at done (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:1004:10) at Object.exports.renderFile (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/jade/lib/index.js:374:12) at View.exports.__express [as engine] (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/jade/lib/index.js:417:11) at View.render (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/view.js:135:8) at tryRender (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/application.js:640:10) at Function.render (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/application.js:592:3) at ServerResponse.render (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:1008:7)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Animation triggered by scrolling is not functioning/displaying div

I'm attempting to make a div fade up when it enters the viewport by using the library found at https://github.com/michalsnik/aos Unfortunately, all that seems to happen is that the div gets hidden. In the head section of my HTML file, I've refe ...

Using Rails to fetch a remote page using AJAX

Currently using Rails3 and attempting to retrieve a remote page via ajax from (https://play.google.com/store/apps/details?id=). $.ajax({ url: app_url, type: 'GET', data: "id=<id>", crossDomain : true, dataType ...

Exploring the functionalities of the execPopulate() method

I'm hitting a roadblock with using execPopulate. I've gone through the documentation, but it's just not clicking for me. Could someone clarify when exactly execPopulate() should be used after populate() and when it's unnecessary? In s ...

Utilizing AJAX and PHP to refresh information in the database

For my project, I need to change the data in my database's tinyint column to 1 if a checkbox is selected and 0 if it is deselected. This is the Javascript/Ajax code I have written: <script> function updateDatabaseWithCheckboxValue(chk,address) ...

Error in jQuery: the variable has not been defined

I am currently working on creating a custom plugin using the code below. I have encountered an error at the line if(options.controls == true) The specific error message says 'options is not defined'. How can I properly define this variable? ( ...

Sharing NPM Scripts Via a Package to be Utilized by Project upon Installation

I have streamlined my linting setup by consolidating all configuration and related packages/plugins/presets (for prettier, stylelint, eslint, commitlint) into an npm package. This allows me to utilize the same setup across multiple projects, simply extendi ...

Frisby.js is looking for a valid JavaScript object, but instead received an undefined value

Struggling to launch a new test using the API testing framework Frisby.js. In my previous tests that didn't involve reading reference files from disk, everything ran smoothly and quickly. The samples provided with Frisby also executed accurately. Thi ...

How to modify the main directory of an ExpressJS application

Currently, I am in the process of setting up the Twilio client quickstart app using nodejs. My setup involves using nginx as a reverse proxy to redirect requests made to http://example.com/calls to localhost:3000 where the Twilio nodejs quickstart is runni ...

What is the best method for using XMLhttpRequest in PHP to append options to a select element?

I'm looking to dynamically fetch values from a MySQL database using PHP and then add them as choices within a select element. Here is my HTML code: <label for='listDivision'>Division</label><select id='listDivision&apos ...

Tips for getting rid of Next.js' default loading indicator

While working on my project using Next.js, I've noticed that whenever I change the route, a default loading indicator appears in the corner of the screen. https://i.sstatic.net/FVWEU.gif Does anyone know how to remove this default loading indicator ...

Issue encountered while importing TypeScript files from an external module in a Next.js project

Encountering an issue within my Next.js project with the following project structure: ├── modules/ │ └── auth/ │ ├── index.ts │ ├── page.tsx │ └── package.json └── nextjs-project/ ├─ ...

Having trouble showing a leaflet map on Node.js Express with Jade

As a newcomer to this technology, I'm currently following a tutorial here. My goal is to generate a map view using jade (although I understand it's now called pug). Within my index.js file, I have set up a router request for the map page. This r ...

What is the best way to utilize the ajax factory method in order to establish a $scoped variable?

One issue I frequently encounter in my controllers is a repetitive piece of code: // Get first product from list Product.get_details( id ) .success(function ( data ) { // Setup product details $scope.active_product = data; }); To avoid this ...

Utilize dynamic Google Maps markers in Angular by incorporating HTTP requests

Struggling to find a solution for this issue, but it seems like it should be simple enough. Initially, I fetch my JSON data using the code snippet below: testApp.controller("cat0Controller", function($scope, $http){ var url = "../../../Data/JSONs/randomd ...

Show the chosen choice in a select dropdown with custom text using Angular

I successfully implemented this code snippet to display a dropdown list of countries and their phone codes. However, I encountered an issue where I need to only show the selected option's code without the country name. The first screenshot shows how i ...

I must retrieve data organized by dates, individual days of the week (Monday through Sunday), and specific hours (1 through 24) in MongoDB

Here is the structure of the MongoDB table records { _id: ObjectId("656efc1366c7dce6da3185e3"), a: '656e5e0c6c773c4374b0b14a', b: '656e5e346c773c4374b0b14b', c: 'abc', d: '656dbcda6c773c4374b ...

Ways to assign an identification attribute to HTML elements within innerHTML

Utilizing Ajax in conjunction with php $("#test1").click( .... function(data){ document.getElementById("test2").innerHTML=data; } ) php will return the data echo "<input type='text' id='test'>"; Seeking adv ...

Guide on how to use a JavaScript AJAX call to download a text file in Java

I am looking to implement a way to download a text file (e.g. 'something.txt') using an AJAX call rather than just an anchor tag in HTML. Here is the HTML code: <body> <a href="#" id="exportViewRule">Export</a> </body&g ...

dc.js bar graph bars blending together

This datetime barChart is causing me some trouble. Interestingly, when I try to replicate the issue in a fiddle (check here), everything functions as expected. Please note that the data takes about 30 seconds to load from github. Below is the code for the ...

Looking for assistance! Seeking the most optimal method to launch a MERN ecommerce platform for production

After completing the development of a multivendor ecommerce web application using the MERN stack, I am now faced with the task of deploying it on Digital Ocean. I am seeking advice on whether to deploy directly on Digital Ocean using Nginx firewall or opt ...