简体   繁体   中英

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:

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM