Skip to content

Res.send not a function

I have an endpoint (using express) which requires me to do some fetching first. Once a parse the response and use res.send I get an error res.send is not a function.

I tried searching for this error but all searches show users had res,req in the wrong order. In this case, mine appear to be right.

Why is it res is not scope after a convert my response to JSON?

router.post("/customerID", async (req, res) => {
  return fetch({endPoint}, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Flowspace-Auth": {myToken},
    },
    body: JSON.stringify({
      query: `query {
        user {
          name
          organizationId
        }
      }`,
    }),
  })
    .then((res) => {
        res.json().then((data) => {
        console.log(data) // This works
        res.send({ data: data }); // res.send is not a function... why, is it not scoped correctly?
      });
    })
    .catch((err) => console.log("unable to fetch:", err));
});

Answer

Your outer response variable is overwritten by your inner result variable. JS goes from the inner most scope to outer most looking for variable. Since, res is already defined in the then clause, that res is used.

Changing it to resp should work.

router.post("/customerID", async (req, resp) => {
  return fetch({endPoint}, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Flowspace-Auth": {myToken},
    },
    body: JSON.stringify({
      query: `query {
        user {
          name
          organizationId
        }
      }`,
    }),
  })
    .then((res) => {
        res.json().then((data) => {
        console.log(data) // This works
        resp.send({ data: data }); // resp will belong to outer response
      });
    })
    .catch((err) => console.log("unable to fetch:", err));
});

You probably want to send something in the catch part too.