Axios -从wesayprint剩余容器生成pdf时出现套接字挂起错误

yc0p9oo0  于 2022-12-12  发布在  iOS
关注(0)|答案(1)|浏览(139)

我已经设置了weasyprint rest容器将html转换为pdf。
下面是nodejs中调用API创建pdf的代码,

const axios = require('axios');
const FormData = require("form-data");
const data = new FormData();

data.append("html", fs.createReadStream(path.join(__dirname, "../assets/html/report.html")));
data.append('asset[]', fs.createReadStream(path.join(__dirname, `../assets/images/footerLogo.png`)))
data.append("style", fs.createReadStream(path.join(__dirname, "../assets/css/report.css")));

const configConvert = {
  url: "https://api.abc.com/pdf",  <== This will be weasyprint api url.
  headers: { ...data.getHeaders()},
  responseType: "arraybuffer",
  method: "post",
  timeout: 3000,
  data: data
};

const pdfResult = await axios(configConvert);
console.log(pdfResult.data)

第一次,它工作得很好,但从第二次我得到这个错误。Weasyprint API在postman中工作得很好。

cause: Error: socket hang up
      at connResetException (node:internal/errors:704:14)
      at TLSSocket.socketOnEnd (node:_http_client:505:23)
      at TLSSocket.emit (node:events:525:35)
      at TLSSocket.emit (node:domain:489:12)
      at endReadableNT (node:internal/streams/readable:1358:12)
      at processTicksAndRejections (node:internal/process/task_queues:83:21) {
    code: 'ECONNRESET'

提前致谢。
我尝试过在axios中设置超时,也添加了https代理保持活动,但面临同样的错误。下面是代码。我还提到了Axios documentation和StackOverflow问题。
第一次

tzdcorbm

tzdcorbm1#

您可以尝试使用nodejs提供的核心httphttps库来调用API,而不是使用Axios。

const https = require('https');
const FormData = require('form-data');
const fs = require('fs');

const data = new FormData();
data.append('html', fs.createReadStream(htmlPath));
data.append('style', fs.createReadStream(cssPath));
var req = https.request({
    'method': 'POST',
    'hostname': '<SOME_HOST>', // weasyprint host in your case
    'path': '<SOME_PATH>', // weasyprint path in your case
    'headers': {
        ...data.getHeaders()
    }
});
req.on('response', (res) => {
    if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
        res.pipe(fs.createWriteStream('generated.pdf'))
        console.log("PDF Saved")
    }
});
data.pipe(req);

这样,HTTP调用就不会抛出Socket Hang up错误。如果需要,可以将代码转换为返回承诺。

相关问题