UnhandledPromiseRejectionWarning:错误:协议错误(Network.setCookies):目标已关闭 - 无法设置Cookie

时间:2018-05-31 06:42:06

标签: node.js puppeteer

目前我遇到了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,但似乎没有任何用处。

1 个答案:

答案 0 :(得分:1)

您遇到错误的原因在于:

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

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

尝试将path设置为'/',或者只是不设置此属性,它就能正常工作。

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