简体   繁体   中英

Sending custom response when get fails with https native module and express

I have an Express application and within it, an HTTP GET request to an API. It works well when there's no error, but when something fails I would like to send a custom response to the client-side through Express:

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

});

The thing is that always sends what res.send({ data: JSON.parse(data) }) resolves to, which is an array of objects when it works, or an empty object {} when it does not. I cannot make work the part of sending 'Something went wrong' if the request fails.

I will appreciate the help. I'm learning.

In your example, when you are calling https://my-api.com , server response is 200 and returns HTML.

Error happens in JSON.parse(data) and it will not get to on("error", ...) part.

You can catch this error like this:

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

otherwise your code works and it returns { data: 'Something went wrong' } on non 200 response

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