如何在 Google Cloud Functions 上使用 Apify [英] How to use Apify on Google Cloud Functions

查看:23
本文介绍了如何在 Google Cloud Functions 上使用 Apify的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Apify 作为 Google Cloud Functions 部署一些代码.触发后,云函数会静默终止.我做错了什么?

I'm deploying some code using Apify as Google Cloud Functions. When triggered, the Cloud Function terminates silently. What am I doing wrong?

我有一些使用 Apify 0.15.1 的工作代码.它在本地运行良好.一旦部署为谷歌云功能,它会静默失败,没有任何明显的错误.使用 Puppeteer 1.18.1 的等效代码可以正常工作.

I have some working code using Apify 0.15.1. It runs fine locally. Once deployed as a Google Cloud Function, it fails silently without any clear error. The equivalent code using Puppeteer 1.18.1 works fine.

我已经使用下面更简单的代码重现了该问题.虽然此示例并不严格要求 Apify,但我希望能够使用 Apify 提供的额外功能.

I've reproduced the issue using more simple code below. While this example doesn't strictly require Apify, I would like to be able to use the extra functionality provided by Apify.

使用 Apify 的代码:

Code using Apify:

const Apify = require("apify");

exports.screenshotApify = async (req, res) => {
  let imageBuffer;
  Apify.main(async () => {
    const browser = await Apify.launchPuppeteer({ headless: true });
    const page = await browser.newPage();

    await page.goto("https://xenaccounting.com");

    imageBuffer = await page.screenshot({ fullPage: true });

    await browser.close();
  });

  if (res) {
    res.set("Content-Type", "image/png");
    res.send(imageBuffer);
  }

  return imageBuffer;
};

使用 Puppeteer 的代码:

Code using Puppeteer:

const puppeteer = require("puppeteer");

exports.screenshotPup = async (req, res) => {
  const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
  const page = await browser.newPage();

  await page.goto("https://xenaccounting.com");

  const imageBuffer = await page.screenshot({ fullpage: true });

  await browser.close();

  if (res) {
    res.set("Content-Type", "image/png");
    res.send(imageBuffer);
  }

  return imageBuffer;
};

一旦部署为 Google Cloud 函数(使用 --trigger-http 和 --memory=2048),Puppeteer 变体工作正常,而 Apify 变体静默终止,没有结果(除了ok"/HTTP 200 返回值).

Once deployed as a Google Cloud Function (with --trigger-http and --memory=2048), the Puppeteer variant works fine, while the Apify variant terminates silently without result (apart from an 'ok' / HTTP 200 return value).

推荐答案

去掉 Apify.main() 函数,它将调用安排到稍后的时间,在你的函数已经返回结果.

Get rid of the Apify.main() function, it schedules the call to a later time, after your function already returned the result.

这篇关于如何在 Google Cloud Functions 上使用 Apify的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆