[SOLVED] How to make a POST request from cloud function?

Hello,

I try to make a post request to my backend from the cloud function. It works when I run it from frontend using fetch.

  const to = "bbbbbcccddd";
  const amount = "12366444444";

  async function requestPay() {
    fetch(`http://localhost:8000/pay`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      },
      body: JSON.stringify({ to, amount }),
    });
  }

image

But it doesn’t work when I run it from cloud.

Moralis.Cloud.define("pay", async () => {
  const to = "bbbbbcccddd";
  const amount = "12366444444";

  Moralis.Cloud.httpRequest({
    method: "POST",
    url: `http://localhost:8000/pay`,
    headers: {
      "Content-Type": "application/json;charset=utf-8",
    },
    body: JSON.stringify({ to, amount }),
  }).then(
    function (httpResponse) {
      logger.info(httpResponse.text);
    },
    function (httpResponse) {
      logger.error("Request failed with response code " + httpResponse.status);
    }
  );
});

The logger just shows that it ran the function, but no errors or data.

My API doesn’t return a response, so I’m not expecting a response. I just want to see the request logged in on the backend how I see it when I send the request from frontend. But the backend doesn’t show anything - meaning the request is not coming.

What am I doing wrong?
Can it be because my backend is on localhost atm? But why would that matter?

Thank you

There is a specific function with httpRequest that you can use in cloud code

Do you mean this function?

  Moralis.Cloud.httpRequest({
    method: "POST",
    url: `http://localhost:8000/pay`,
    headers: {
      "Content-Type": "application/json;charset=utf-8",
    },
    body: JSON.stringify({ to, amount }),
  }).then(
    function (httpResponse) {
      logger.info(httpResponse.text);
    },
    function (httpResponse) {
      logger.error("Request failed with response code " + httpResponse.status);
    }
  );

Yes, this function. Should work

you can not make a request to localhost from a cloud function as the function runs on another server.

1 Like

Okay, got it thank you. I’ll try again when I deploy it and write if something.

1 Like