主要图像难题 - Node.js Express 服务器

Major images conundrum - Node.js Express server

所以我们有一个带有 Node.js 的后端工具,可以为 img 标签抓取 HTML 网页。我们使用 worker child_process 来执行此操作,以免阻塞主进程。我们在服务器上执行此操作的原因是因为我们在尝试使用 AJAX / 和 Angular $http.

访问 HTML 页面时遇到 CORS 问题

后端网络抓取程序完成后,它可以向浏览器发送 url 列表。浏览器可以对与这些 url 相关的图像发出 AJAX 请求,但据我所知,前端会遇到与检索 HTML.

相同的 CORS 问题。

所以我们目前对这个问题有一个相当糟糕的解决方案。我们使用 Cloudinary 来完成繁重的工作,而不是我们的 Node.js 服务器处理 base64。后端工作人员 child_process 抓取 HTML,获取图像 url,然后向 Cloudinary 发送请求以检索图像并将新的 Cloudinary url 发回我们的服务器。然后我们将 Cloudinary url 发送到前端,前端可以访问这些 Cloudinary url 而不会出现任何 CORS 问题。

这有两个问题:

  1. This is fairly slow - scraping takes about 2 seconds and then waiting for Cloudinary to save the images and respond is another 2-4 seconds. So the browser has to wait for about 4-6 seconds.
  2. We end up storing a lot of images in Cloudinary which will get expensive. We can end up deleting about 90% of the images we save immediately after this process, because the user is only going to select one of the images that appear in the browser, but we are worried about the costs that might be incurred even if the images reside on Cloudinary for a few seconds.

有没有人遇到过这些问题并认为他们有比我们正在使用的解决方案更好的解决方案?

Return 将抓取的图像列表发送给您的客户端,然后使用您的 nodejs 服务器作为代理来提供这些图像。

这是一个使用 request 模块的简单示例:

http.createServer(function (req, resp) {
  var x = request('http://example.com/image.png')
  req.pipe(x)
  x.pipe(resp)
})

您的客户随后可以访问任何想要的图像:

domain.com/proxy?url=http://example.com/image.png

将我的评论作为答案,因为这似乎是适合您的解决方案。

您可以让服务器从页面中抓取图像 URL,然后将 URL 列表发送给客户端。然后,客户端可以使用这些 URL 动态地将 <img> 标记插入当前页面,浏览器将显示图像。

<img> 标记 URL 没有跨域限制。

这样做,不需要尝试从客户端下载 Ajax 的图像,因此没有 CORS 问题。您的服务器执行跨源抓取。然后客户端只需插入 <img> 标签,其中包含抓取的 URL。


此技术 "borrows" 来自其他站点的图像,然后使用它们的带宽将它们显示在您的页面中。您可能应该确保这是对这些图像的允许使用。