首页 > 解决方案 > UnhandledPromiseRejectionWarning:错误:协议错误(Network.setCookies):目标已关闭 - 无法设置 cookie

问题描述

目前我遇到了一个问题,即 Puppeteer 在使用 setCookies 方法时崩溃。我目前正在使用 Puppeteer v 1.4.0(撰写本文时的最新版本)以及与 Puppeteer 捆绑的 Chromium 版本,这是给我带来麻烦的代码:

const puppeteer = require('puppeteer');
const moment = require('moment');
(async () => {
  const browser = await puppeteer.launch(
    {
      headless: false
    }
  );
  const page = await browser.newPage();
  await page.goto('https://google.com');
  const currentUrl = await page.url();
  await browser.close();
  const browser1 = await puppeteer.launch(
    {
      headless: false
    }
  );
  const page1 = await browser1.newPage();
  const cookie = await currentUrl.split("/");
  await page1.setCookie({
    'name': 'samplename',
    'value': cookie[0],
    'domain': 'sampledomain',
    'path': cookie[0] + '/' + cookie[0] + '/' + cookie[0],
    'expires': moment().add(21, 'days').valueOf(),
    'httpOnly': false,
    'secure': true,
    'sameSite': "Lax"
  });
  await page1.goto(currentUrl);
})();

这是错误消息

(node:64704) UnhandledPromiseRejectionWarning: Error: Protocol error (Network.setCookies): Target closed.
    at Promise (/Users/pc/Desktop/Shopify Bot/node_modules/puppeteer/lib/Connection.js:200:56)
    at new Promise (<anonymous>)
    at CDPSession.send (/Users/pc/Desktop/Shopify Bot/node_modules/puppeteer/lib/Connection.js:199:12)
    at Page.setCookie (/Users/pc/Desktop/Shopify Bot/node_modules/puppeteer/lib/Page.js:320:26)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:182:7)
(node:64704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:64704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我已经自己研究了一段时间,并且多个消息来源似乎说实际上没有执行异步是问题,但是,我相信我正在异步运行所有内容(但是,因为这是我第一次做任何事情在 NodeJS 上异步,我可能会在判断中犯严重错误)。我已经尝试验证我的 Chromium 并卸载 + 重新安装 Puppeteer,但似乎没有任何效果。

标签: node.jspuppeteer

解决方案


你得到一个错误的原因是在这一行:

'path': cookie[0] + '/' + cookie[0] + '/' + cookie[0],

它解析为https:/https:/https:哪个不是此属性的有效值。

尝试设置path'/'不设置此属性,它会正常工作。

path 您可以在此处此处找到有关如何使用的更多信息。


推荐阅读