简体   繁体   English

Node.js:意外的标记“.” 尝试在花括号中传递全局变量时

[英]Node js: Unexpected token '.' when trying to pass a global variable in curly braces

I am using the package got to fetch pages from a website.我正在使用 package网站获取页面。

The website sets a new session cookie on every request so in order to stay logged in I need to use a cookie jar.该网站为每个请求设置一个新的 session cookie,因此为了保持登录状态,我需要使用 cookie jar。

Here is the example for how to use a cookie jar from the got documentation:以下是如何使用 got 文档中的 cookie jar 的示例:

const {promisify} = require('util');
const got = require('got');
const {CookieJar} = require('tough-cookie');

(async () => {
    const cookieJar = new CookieJar();
    const setCookie = promisify(cookieJar.setCookie.bind(cookieJar));

    await setCookie('foo=bar', 'https://example.com');
    await got('https://example.com', {cookieJar});
})();

In my case however, because the cookie gets reset after every request and requests can be made at any time from many different areas of my script I have defined my cookie jar as a global variable, like so: global.cookieJar = new CookieJar();然而,在我的例子中,因为每次请求后 cookie 都会重置,并且可以随时从脚本的许多不同区域发出请求,所以我将 cookie jar 定义为全局变量,如下所示: global.cookieJar = new CookieJar(); . .

However, I find myself unable to pass the global variable to the got() function. Got's documentation only shows passing the cookie jar to the got() function by placing it in curly brackets.但是,我发现自己无法将全局变量传递给got() function。Got 的文档仅显示通过将 cookie jar 放在大括号中将其传递给got() function。 Therefore, I should be able to pass the variable like: await got('https://example.com', {global.cookieJar}) .因此,我应该能够像这样传递变量: await got('https://example.com', {global.cookieJar}) But, if the variable in the curly brackets contains .但是,如果大括号中的变量包含. () javascript throws an SyntaxError: Unexpected token '.' () javascript 抛出SyntaxError: Unexpected token '.' and does not allow the code to be executed.并且不允许执行代码。

How can I pass global.cookieJar to got() without causing a syntax error?如何将global.cookieJar传递给got()而不会导致语法错误?

The syntax:语法:

const foo = 1;
const object = { foo };

is shorthand for:是以下内容的简写:

const foo = 1;
const object = { foo: foo };

There are two issues with:有两个问题:

{global.cookieJar}
  • An identifier cannot have a .标识符不能有. in it (hence your syntax error)在其中(因此您的语法错误)
  • The property name the function you are passing the object to is looking for is cookieJar , not global.cookieJar .您将 object 传递给正在寻找的属性名称 function 是cookieJar ,而不是global.cookieJar

Don't use the shorthand.不要使用简写。

{cookieJar: global.cookieJar}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM