Home > Mobile >  Express Routes - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Express Routes - Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Time:11-05

Hey I am creating a route for my MERN app in which I wanted to do TWO find mongoose queries back to back. I first find a entry in the params model with the same clipname and this entry contains a element field(defined in its schema). Then I want to find another entry in elements model with the same element name. But I run into this error. Can somebody help me. Thnx

const elementstemplate = require("../models/elements.js");
const paramstemplate = require("../models/params.js");

router.get("/getparams/:clipName", async (req, res) => {
  paramstemplate
    .findOne({ clipName: req.params.clipName })
    .then((params) => {
      
      const fetchedelement = params.element;
      res.json(params);
    })
    .then((fetchedelement) => {
      elementstemplate
        .findOne({ elementName: fetchedelement })
        .then((elementdata) => {
          res.json(elementdata);
         
        });
    });
});

CodePudding user response:

You can't send 2 responses in one request. Return fetchedElement in first .then(). Handle it in second and then send both as json back to the client. But if your callback function is async you could work with await instead of using .then().

CodePudding user response:

Expanding on the previous answer (https://stackoverflow.com/a/69832516/177397), it will be a lot cleaner if you take advantage of async/await. That way, you just need to call the two queries, one after the other. You can then return the data in an object in the response. Here's how your code would look when converted to async/await:

    const elementstemplate = require("../models/elements.js");
    const paramstemplate = require("../models/params.js");

    router.get("/getparams/:clipName", async (req, res) => {
      // Get the params
      const params = await paramstemplate.findOne({ clipName: req.params.clipName });
      
      // Get the element data
      const fetchedelement = params.element;
      const elementdata = await elementstemplate.findOne({ elementName: fetchedelement });
      
      // Return an object with both the params and the element data
      return res.json({ params, elementdata});
    });
  • Related