NodeJS 的图像下载问题

Image download issue with NodeJS

我正在尝试使用 axios 下载 Google 书页,代码如下:

const response = await axios({
        method: 'GET',
        url: url,
        responseType: 'stream'
    })

这适用于某些图像(例如 this one) but fails for some others (like this one)。 Google 不提供实际图像,而是提供默认的 "Image not available" 文件。

两个请求在浏览器中都有效,但第二个请求在 NodeJS 中失败。

我比较了两个请求的请求和响应 headers,但没有看到任何相关信息;请注意,两个图像都是 PNG。到目前为止,我不记得 JPEG 遇到过这个问题。

为什么 Google 没有正确提供第二张图片

欢迎使用以下代码在家试用:

const axios = require('axios');
const fs = require('fs');

(async function () {
    const response = await axios({
        method: 'GET',
        url: 'https://books.google.fr/books/content?id=DvGApMzEJmQC&hl=fr&pg=PA61&img=1&zoom=3&sig=ACfU3U3IPtY0MOIxgMR8rJTxt9YYGPUl1Q&w=1025',
        responseType: 'stream'
    })
    response.data.pipe(fs.createWriteStream('result.png'))

    return new Promise((resolve, reject) => {
        response.data.on('end', () => {
            resolve();
        })
        response.data.on('error', () => {
            reject();
        })
    })
})();

我终于找到了一个解释,虽然它并没有解开全部谜团。

Google 不提供第二个文件,除非 NID cookie 随请求一起提供。 每 Google's policies

The NID cookie contains a unique ID Google uses to remember your preferences and other information, such as your preferred language (e.g. English), how many search results you wish to have shown per page (e.g. 10 or 20), and whether or not you wish to have Google’s SafeSearch filter turned on.

现在我想知道两件事:

  • 为什么甚至需要它作为浏览自定义 cookie?是否用于安全搜索?
  • 为什么只有几个文件需要它?

无论如何,这是我的问题的解决方案:

const initialRequest = await axios({
        method: 'GET',
        url: 'https://google.com'
    })

    const response = await axios({
        method: 'GET',
        url: 'https://books.google.com/books/content?id=DvGApMzEJmQC&pg=PA61&img=1&zoom=3&sig=ACfU3U3IPtY0MOIxgMR8rJTxt9YYGPUl1Q&w=1025',
        responseType: 'stream',
        headers:{
            'Cookie' : initialRequest.headers['set-cookie']
        }
    })