Home > Mobile >  Res.send not a function
Res.send not a function

Time:12-22

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));
});

CodePudding user response:

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.

CodePudding user response:

You are calling send method on the response of the fetch api call on which the send method is not available. find the correct code below.

    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((response) => {
        response.json().then((data) => {
        console.log(data); // This works
        res.send({ data: data }); 
        });
    })
    .catch((err) => console.log("unable to fetch:", err));
});
  • Related