如何处理Node.js中的https.get错误并防止应用崩溃?

时间:2018-10-28 19:16:47

标签: node.js api asynchronous

我是第一次使用Node.js,并且正在使用CloudConvert API。我已经创建了Express应用,并且能够上传文件,然后将其发送到API。然后,我等待来自CloudConvert API的响应并处理该响应并下载转换后的文件。

当前,该文件会立即下载,但是当CloudConvert触发回调时,它会由于TypeError [ERR_INVALID_DOMAIN_NAME]: Unable to determine the domain name而崩溃。

如何设置这些https.get调用,以便它们处理错误?

router.get('/cloud-callback', function(req, res) {
  let request = https.get(`https:${req.query.url}`, function(response) {
    console.log("got response:" + response.statusCode);
    response.on("data", function(data) {
    let resData = JSON.parse(data.toString());
    let fileUrl = `https:${resData.output.url}`;
    let file = fs.createWriteStream("./data/rtfs/sample.rtf");

    let ccRequest = https.get(fileUrl, function(ccResponse) {
      ccResponse.pipe(file);
      }).on('error', (error) => console.log(error.message));;
    }).on('error', (error) => console.log(error.message));
  });
});


router.post('/convert2RTF/:filename', function(req, res) {
  const file = __basedir + "/data/" + req.params.filename + ".pdf";
  console.log("hi", file);
  cloudconvert.convert({
    "inputformat": "pdf",
    "outputformat": "rtf",
    "input": "download",
    "save": false,
    "file": "https://z620a87c.ngrok.io/sample.pdf",
    "callback": "https://z620a87c.ngrok.io/files/cloud-callback"
  });
  res.redirect(301,'/files');
});

0 个答案:

没有答案