yasarui
yasarui

Reputation: 6573

ENOTFOUND issue on https get request

In my application I'm trying to hit an end point using https and then getting the response.

Route file:

router.get("/get-details", (req, res) => {
  sampleController.getDetails()
    .then((data) => {
      console.log("Data is ", data);
      res.send(data);
    })
    .catch(() => {
      res.status(500).json({
        success: false,
        data: null,
        message: "Failed to lookup the data",
      });
    });
});

Controller file:

const getDetials = () => {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: "https://jsonplaceholder.typicode.com/",
      path: "posts",
      method: "GET",
    };

    const req = https.request(options, (res) => {
      console.log(`statusCode: ${res.statusCode}`);

      res.on("data", (d) => {
        process.stdout.write(d);
      });
    });

    req.on("error", (error) => {
      console.log("Error is ", error);
      reject(error);
    });

    req.end();
  });
};

I am getting this error:

enter image description here

Not sure where I'm making the mistake. Does somebody know what I'm getting wrong here?

Upvotes: 0

Views: 40

Answers (1)

Harshana
Harshana

Reputation: 5496

Try setting up the URL without the protocol and add / in front of the path in options object:

 const options = {
      hostname: "jsonplaceholder.typicode.com",
      path: "/posts",
      method: "GET",
    };

Full example:

const getDetials = () => {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: "jsonplaceholder.typicode.com",
      path: "/posts",
      method: "GET",
    };

    const req = https.request(options, (res) => {
      console.log(`statusCode: ${res.statusCode}`);

      res.on("data", (d) => {
        process.stdout.write(d);
      });
    });

    req.on("error", (error) => {
      console.log("Error is ", error);
      reject(error);
    });

    req.end();
  });
};

Upvotes: 1

Related Questions