在线部署nodejs服务器时请求超时

编程入门 行业动态 更新时间:2024-10-05 21:20:18

<a href=https://www.elefans.com/category/jswz/34/1770935.html style=在线部署nodejs服务器时请求超时"/>

在线部署nodejs服务器时请求超时

我有这段代码的两部分,我不确定错误来自哪里或如何诊断它,我的代码在我的本地主机上运行良好并正确返回数据并且它毫无问题地显示在我的前端。

当我将服务器部署到 render(免费计划)时,我遇到了这个问题

[错误:请求超时。]

我试过像这样修复服务器的根目录

const server =  app.listen(port, () => {
  console.log(`Running server at port: ${port}`);
});

server.setTimeout(120000); // 120 seconds timeout

然后在 api 端点上有 2 个函数,由于这个问题添加了 axios 超时功能,对于 ffmepg 我不确定如何修复它

router.post("/", async (req, res) => {
  var videoUrl = req.body.video;

  const videoResponse = await axios.get(videoUrl, {
    responseType: 'arraybuffer',
  });

  const formData = new FormData();
  formData.append('file', Buffer.from(videoResponse.data), {
    filename: 'video.mp4',
  });
  formData.append('model', model);
  formData.append('response_format', 'srt');

  const headers = {
    'Authorization': `Bearer ${token}`,
    ...formData.getHeaders(),
  };

  const response = await axios.post('', formData, {
    headers,
      timeout: 1200000
  });

  fs.writeFileSync('transcription.srt', response.data);
  console.log('Transcription saved to transcription.srt');

  const subtitlePath = "./transcription.srt";
  console.log('subtitlePath :', subtitlePath);

  const randomNum = Math.floor(100000000000 + Math.random() * 900000000000);
  const fileName = `video_${randomNum}.mp4`;
  const outputPath = `./${fileName}`;

  // Execute the ffmpeg command to burn the subtitles into the video
  const ffmpeg = spawn("ffmpeg", [
    "-i",
    "pipe:0",
    "-vf",
    `subtitles=${subtitlePath}:force_style='Alignment=10,OutlineColour=&H100000000,BorderStyle=3,Outline=1,Shadow=0,Fontsize=10'`,
    "-c:a",
    "copy",
    "-progress", "pipe:1",
    outputPath,
  ]);

  // Pipe the videoResponse array buffer to FFmpeg
  ffmpeg.stdin.write(videoResponse.data);
  ffmpeg.stdin.end();

  // Send the output file as a response once the process is complete
  ffmpeg.on("close", () => {
    fs.readFile(outputPath, (err, data) => {
      if (err) {
        console.error(err);
        res.status(500).send("Failed to read the file");
      } else {
        res.set({
          "Content-Disposition": `attachment; filename=${outputPath}`,
          "Content-Type": "application/octet-stream",
        });
        res.send(data);
        console.log("File sent successfully");
        // Delete the output file once it has been sent
        fs.unlinkSync(outputPath);
      }
    });
  });
});

module.exports = router;

在我的 React Native 应用程序中,我添加了 promise 和一些超时代码,只是为了确保错误不是源自那里,但仍然面临同样的问题

testing = (downloadURL) => {
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => {
        reject(new Error('Request timed out'));
      }, 120000); // 120 seconds timeout
    });

    this.setState({ loading: true, uploading: false });
    RNFetchBlob.config({
      fileCache: true,
      appendExt: 'mp4',
    })
      .fetch('POST', '', {
        'Accept': 'application/octet-stream',
        'Content-Type': 'application/json',
      }, JSON.stringify({
        video: downloadURL,
      }))
      .then(response => {
        const videoPath = response.path();
        const videoUrl = `file://${videoPath}`;
        console.log('videoUrl :', videoUrl);
        this.setState({ loading: false, success: true, render: videoUrl, downloadURL: null });
      })
      .catch(error => {
        console.log(error);
        this.setState({
          error: error.message,
          loading: false,
        });
      })
      .finally(() => {
        clearTimeout(timeoutId);
      });

    const timeoutId = setTimeout(() => {
      console.log('Request timed out');
      this.setState({
        error: 'Request timed out',
        loading: false,
      });
    }, 120000); // 120 seconds timeout

    Promise.race([timeoutPromise])
      .catch(error => {
        console.log(error);
        this.setState({
          error: error.message,
          loading: false,
        });
      });
  };

现在来描述这个问题,在触发端点之后,api运行良好然后启动axios post请求,这部分非常快并且在大约2-3秒内完成,然后将文件移动到ffmpeg进行转换,我有下面的代码允许我检查转换状态进度,通常从我看到的是当百分比即将达到 100% 时,我的前端和服务器上显示的错误超时

POST /api/v1/test - - 毫秒 - -

控制台日志上没有错误 whatesover

   // Listen to stderr and stdout data events to check the progress of the conversion
  let progress = 0;
  let duration = 0;
  ffmpeg.stderr.on('data', (data) => {
    // Search for the "Duration" line to get the total duration
    const durationMatch = /Duration: (\d{2}):(\d{2}):(\d{2})/.exec(data.toString());
    if (durationMatch) {
      duration = (parseInt(durationMatch[1]) * 3600) + (parseInt(durationMatch[2]) * 60) + parseInt(durationMatch[3]);
    }

    // Search for the "time=" line to get the current time
    const timeMatch = /time=(\d{2}):(\d{2}):(\d{2})/.exec(data.toString());
    if (timeMatch) {
      const currentTime = (parseInt(timeMatch[1]) * 3600) + (parseInt(timeMatch[2]) * 60) + parseInt(timeMatch[3]);
      progress = Math.floor((currentTime / duration) * 100);
      console.log(`FFmpeg     : ${progress}%`);
    }
  });

请帮忙。任何建议表示赞赏

回答如下:

更多推荐

在线部署nodejs服务器时请求超时

本文发布于:2024-05-30 07:15:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在线   时请   服务器   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!