【问题标题】:ENOTFOUND issue on https get requesthttps 获取请求上的 ENOTFOUND 问题
【发布时间】:2021-03-20 11:09:25
【问题描述】:

在我的应用程序中,我尝试使用 https 到达终点,然后获得响应。

路线文件:

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

控制器文件:

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

我收到此错误:

不知道我在哪里犯了错误。有人知道我在这里做错了什么吗?

【问题讨论】:

    标签: javascript node.js https


    【解决方案1】:

    尝试设置不带协议的 URL,并在选项对象的路径前添加/

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

    完整示例:

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

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 2019-02-15
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 2020-05-31
      相关资源
      最近更新 更多