代码之家  ›  专栏  ›  技术社区  ›  Peter

使用https本机模块和express在get失败时发送自定义响应

  •  0
  • Peter  · 技术社区  · 5 年前

    我有一个Express应用程序,其中有一个对API的httpget请求。

    const https = require('https');
    
    // more code: init express, middlewares, etc
    
    app.get('/my-endpoint', async (req, res) => {
    
      https.get('https://my-api.com', (resp) => {
        let data = '';
    
        resp.on('data', (chunk) => {
          data += chunk;
        });
    
        resp.on('end', () => {
          console.log(JSON.parse(data));
          res.send({ data: JSON.parse(data) })
        });
    
      }).on("error", (err) => {
        console.log("Error: " + err.message);
        res.send({ data: 'Something went wrong' })
      });
    
    });
    

    res.send({ data: JSON.parse(data) }) 解析为,即工作时的对象数组或空对象 {} 'Something went wrong'

    我会感激你的帮助。我在学习。

    0 回复  |  直到 5 年前
        1
  •  0
  •   Ján Smolko    5 年前

    在你的例子中,当你打电话的时候 https://my-api.com ,服务器响应为200并返回HTML。

    错误发生在 JSON.parse(data) on("error", ...) 部分。

    您可以这样捕获此错误:

    resp.on("end", () => {
      try {
        console.log(JSON.parse(data));
        res.send({ data: JSON.parse(data) });
      } catch (e) {
        res.send({ data: "Something went wrong" });
      }
    });
    

    { data: 'Something went wrong' }

    推荐文章