Home > OS >  Error: Cannot remove headers after they are sent to the client
Error: Cannot remove headers after they are sent to the client

Time:11-24

I was working on admin registration and admin data retrieving react app. The registration works fine but retrieving admin data is crushing my backend. I have encountered this error when call the given endpoint from my react app. But when I call it from Postman it works very fine. And when I see the console on my browser my react app sends two calls simultaneously instead of one. On these calls my app crushes. If any one can show me how to solve this problem? For backend = Node.js with express.js framework For frontend = React

This is the error I am getting

node:internal/errors:465
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client    
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.removeHeader (node:_http_outgoing:654:11)
    at ServerResponse.send (C:\Users\Momentum\Documents\The Technologies\Madudi-App-Api\node_modules\express\lib\response.js:214:10)
    at C:\Users\Momentum\Documents\The Technologies\Madudi-App-Api\api\index.js:22:72
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

This is how I setup my endpoint and changed the data to a string in order to get simple response but it crushes

const makeHttpRequest = (controller, helper) => {

  const makeRequest =  (req, res) => {
    try {
      var data =  "Trying response";
      res.status(200).send({ status: true, data: data });
    } catch (error) {
      console.log(`ERROR: ${error.message}`);
      res.status(400).send({ status: false, error: error.message });
    }
  };
  return { makeRequest };
};

const makeApi = ({router, controller, helper}) => {
    router.get("/test", (req, res) => res.send("Router is Woking..."));
    
    router.get("/admin/get_all_admins", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));
}
 
module.exports = { makeApi }

And this is the call from my react app

export default  function GetAllUsers() {
 useEffect(() =>{
    try{
        const response =  axios.get('http://localhost:5000/admin/get_all_admins').then(async (response) => {
            console.log('response  ', response)
            return response.data; 
        });
      
    }catch(error) {
        return [];
    }
 }, [])
  

CodePudding user response:

I am not familiar with this way of setting up the server. Looks strange to me. However, in router.get("/admin/get_all_admins" your sending a response which calls a function makeHttpRequest that also sends a response. Thus you get an error Cannot remove headers after they are sent to the client because you're sending a response twice.

CodePudding user response:

This particular error happens when you try to send more than one response for the same incoming request (something you are not allowed to do).

You are calling res.send() more than one for the same request on your server.

The first happens in the makeRequest() function.

The second time happens in this line of code:

router.get("/admin/get_all_admins", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));

You can't do that. You get ONE response per incoming request. So, either send the response in makeRquest() and don't send it in the caller. Or, don't send the response in makeRequest() and just return what the response should be and let the caller send it. Pick one model or the other.

  • Related