How to use the CookieJar function from tough-cookie

Find comprehensive JavaScript tough-cookie.CookieJar code examples handpicked from public code repositorys.

tough-cookie.CookieJar is a class in the tough-cookie library that provides an interface for managing and interacting with HTTP cookies.

11
12
13
14
15
16
17
18
19
20
var tough = require("tough-cookie");
var Cookie = tough.Cookie;
var cookie = Cookie.parse(header);
cookie.value = "somethingdifferent";
header = cookie.toString();
var cookiejar = new tough.CookieJar();

// Asynchronous!
var cookie = await cookiejar.setCookie(
  cookie,
fork icon138
star icon820
watch icon49

+ 7 other calls in file

8
9
10
11
12
13
14
15
16
17
var Cookie = cookies.Cookie;
var cookie = Cookie.parse(header);
cookie.value = 'somethingdifferent';
header = cookie.toString();

var cookiejar = new cookies.CookieJar();
cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb);
// ...
cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) {
  res.headers['cookie'] = cookies.join('; ');
fork icon138
star icon1
watch icon2

+ 2 other calls in file

How does tough-cookie.CookieJar work?

tough-cookie.CookieJar is a class provided by the tough-cookie library that represents a container for HTTP cookies. It provides an interface for managing and interacting with cookies, including adding and removing cookies, serializing and deserializing cookies, and inspecting cookies. To use tough-cookie.CookieJar, developers first need to import the tough-cookie library and create a new instance of the CookieJar class. Once the CookieJar instance is created, developers can use the various methods provided by the class to manage and interact with cookies. For example, they can add a new cookie to the jar using the setCookie method, retrieve all cookies that match a particular URL using the getCookies method, and serialize the cookies in the jar to a string using the serializeSync method. The CookieJar class also provides a number of options for configuring its behavior, including options for setting the default domain and path for cookies, enabling or disabling cookie security features, and specifying custom cookie stores for persistent storage. Overall, tough-cookie.CookieJar is a powerful tool for managing and interacting with HTTP cookies in JavaScript applications, and is used by a variety of libraries and frameworks to implement cookie-based authentication and other features.

27
28
29
30
31
32
33
34
35
36
const logo = fs.readFileSync(path.join(__dirname, 'logo.txt'), 'utf8');

// try persistent cookie
const cookiePath = path.join(process.cwd(), '.cookie.json');
touch.sync(cookiePath);
const jar = new tough.CookieJar(new FileCookieStore(cookiePath));

const req = axios.create({
  timeout: 35e3,
  headers: {
fork icon85
star icon358
watch icon27

+ 3 other calls in file

9
10
11
12
13
14
15
16
17
18
const FAKE_APP_URI = 'https://yourdomain.heap/';

(function(document) {
  const store = new WebStorageCookieStore(localStorage);

  const cookiejar = new tough.CookieJar(store);
  Object.defineProperty(document, "cookie", {
    get() {
      return cookiejar.getCookieStringSync(FAKE_APP_URI);
    },
fork icon28
star icon35
watch icon5

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const tough = require("tough-cookie");

// Create a new CookieJar instance
const jar = new tough.CookieJar();

// Set a new cookie in the jar
const cookie = new tough.Cookie({
  key: "myCookie",
  value: "myValue",
  domain: "example.com",
  path: "/",
  httpOnly: true,
});
jar.setCookie(cookie, "http://example.com", (err, cookie) => {
  if (err) throw err;
  console.log("Cookie set successfully!");
});

// Get all cookies that match a given URL
jar.getCookies("http://example.com", (err, cookies) => {
  if (err) throw err;
  console.log("Cookies found:", cookies);
});

// Serialize the cookies in the jar to a string
const serializedCookies = jar.serializeSync();
console.log("Serialized cookies:", serializedCookies);

In this example, we first import the tough-cookie library using the require function, and create a new instance of the CookieJar class. We then set a new cookie in the jar using the setCookie method, which takes a Cookie object and a URL as arguments. We provide a new Cookie object with some example properties, including a name, value, domain, and path, and specify the URL for which the cookie should be set. We also provide a callback function to handle errors and log a message when the cookie is successfully set. Next, we use the getCookies method to retrieve all cookies that match a given URL, which returns an array of Cookie objects. We provide the URL to match as an argument, and provide a callback function to handle errors and log the results. Finally, we use the serializeSync method to serialize the cookies in the jar to a string, which can be saved or transmitted as needed. We log the serialized string to the console using console.log. This demonstrates how tough-cookie.CookieJar can be used to manage and interact with HTTP cookies in a Node.js application, including setting, retrieving, and serializing cookies.

4
5
6
7
8
9
10
11
12
13
const delay = require('./lib/delay');
const log = require('./lib/logging');
const { CookieJar } = require('tough-cookie');
const UserAgent = require('user-agents');

const cookieJar = new CookieJar(); // Automatically parse and store cookies
const challengeInProgress = {};

// Got instance to handle cloudflare bypass
const instance = got.extend({
fork icon15
star icon130
watch icon5

+ 3 other calls in file

73
74
75
76
77
78
79
80
81
82
if (this.config.interval < 0.5) {
  this.log.info("Set interval to minimum 0.5");
  this.config.interval = 0.5;
}

this.cookieJar = new tough.CookieJar();
const cookieState = await this.getStateAsync("auth.cookie");
if (cookieState && cookieState.val) {
  this.cookieJar = tough.CookieJar.fromJSON(cookieState.val);
}
fork icon5
star icon16
watch icon8

+ 3 other calls in file

19
20
21
22
23
24
25
26
27
28
29
30
31
32




// axios-cookiejar-support v2.0.2 syntax
const { wrapper: axiosCookieJarSupport } = require('axios-cookiejar-support'); // as of axios-cookiejar-support v2.0.x, see https://github.com/3846masa/axios-cookiejar-support/blob/main/MIGRATION.md
const tough = require('tough-cookie');
const cookieJar = new tough.CookieJar();




const axios = require('axios') //.default;	// https://github.com/axios/axios
axios.defaults.xsrfCookieName = undefined; // change  xsrfCookieName: 'XSRF-TOKEN' to  xsrfCookieName: undefined, we do not want this default,
fork icon4
star icon24
watch icon5

+ 4 other calls in file

2
3
4
5
6
7
8
9
10
11
12
13
const { HttpCookieAgent, HttpsCookieAgent } = require('http-cookie-agent/http');


var Controller = function (hostname, port, unifios, ssl) {


    var _self = this;
    _self._cookieJar = new CookieJar();
    _self._unifios = unifios;
    _self._ssl = ssl;
    _self._baseurl = 'https://127.0.0.1:8443';

fork icon18
star icon43
watch icon8

307
308
309
310
311
312
313
314
315
316
317
    return makeApolloClient(serverUrl, TESTS_LOG_REQUEST_RESPONSE || logErrors)
}


const createAxiosClientWithCookie = (options = {}, cookie = '', cookieDomain = '') => {
    const cookies = (cookie) ? cookie.split(';').map(Cookie.parse) : []
    const cookieJar = new CookieJar()
    const domain = (urlParse(cookieDomain).protocol || 'http:') + '//' + urlParse(cookieDomain).host
    cookies.forEach((cookie) => cookieJar.setCookieSync(cookie, domain))
    const httpsAgentWithUnauthorizedTls = new https.Agent({ rejectUnauthorized: false })
    if (TESTS_TLS_IGNORE_UNAUTHORIZED) options.httpsAgent = httpsAgentWithUnauthorizedTls
fork icon12
star icon33
watch icon10

+ 3 other calls in file

52
53
54
55
56
57
58
59
60
61
  delete site.cookies
}
async function backoffFetch (uri, opts) {
  if (state.inflight[uri]) return state.inflight[uri]
  const site = siteConfig(uri, config)
  if (!site.cookieJar) site.cookieJar = new CookieJar()
  state.inflight[uri] = enqueue(fetch, uri, {cookieJar: site.cookieJar, ...opts})
  try {
    return await state.inflight[uri]
  } finally {
fork icon0
star icon3
watch icon1

+ 3 other calls in file

106
107
108
109
110
111
112
113
114
115
opts.method = method;
opts.headers = {};
opts.retry = 0;
opts.responseType = 'buffer';
opts.maxRedirects = 21;
opts.cookieJar = new CookieJar();
opts.ignoreInvalidCookies = true;
opts.forever = nodeHTTPPersistent;
if (msg.requestTimeout !== undefined) {
    if (isNaN(msg.requestTimeout)) {
fork icon0
star icon1
watch icon1

21
22
23
24
25
26
27
28
29
30
}

async #init() {
	if (this.#request === undefined) {
		const options = {
		    cookieJar: new CookieJar(),
		    hooks: {
		        afterResponse: [
		        	addJSDOMToResponse,
		            (response) => {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

31
32
33
34
35
36
37
38
39
40
41
    // 일반실 예약 가능 여부
    general_admission = false
}


class Korail{
    cookieJar = new CookieJar();
    headers = {
        "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 5.1.1; Nexus 4 Build/LMY48T)",
        "Referer": "https://www.letskorail.com/korail/com/loginAction.do",
        "Content-Type": "application/x-www-form-urlencoded"
fork icon0
star icon0
watch icon2

+ 2 other calls in file

78
79
80
81
82
83
84
85
86
}

const type = typeMap[typeParam];

// 获取cookie
const cookieJar = new CookieJar();
await got(site + '/main.do', {
    cookieJar,
});
fork icon0
star icon0
watch icon1

+ 2 other calls in file

29
30
31
32
33
34
35
36
37
38
39
  res.send('You are not authenticated so far. Call /login first');
  //res.redirect("/login")
}


function initChurchToolsClient() {
    churchtoolsClient.setCookieJar(axiosCookieJarSupport.default, new tough.CookieJar());
    churchtoolsClient.setBaseUrl(config.get('churchtools.url'));
    var logLevel = config.get('logging.level');
    if(logLevel == "debug") {
      // LOG_LEVEL_DEBUG (outputs every request and response including request/response data)
fork icon0
star icon0
watch icon0

+ 3 other calls in file

11
12
13
14
15
16
17
18
19
20
const { topicPath } = ctx.params;
const link = `${baseUrl}/${topicPath ? topicPath : 'latest'}`;

let cookieJar = await ctx.cache.get('pnas:cookieJar');
const cacheMiss = !cookieJar;
cookieJar = cacheMiss ? new CookieJar() : CookieJar.fromJSON(cookieJar);
const { data: res } = await got(link, {
    cookieJar,
});
if (cacheMiss) {
fork icon0
star icon0
watch icon0

0
1
2
3
4
5
6
7
8
9
const tough = require('tough-cookie')
const each = require('aigle/each')

module.exports = async (instance) => {
  let cookies = await instance.cookies()
  let cookiejar = new tough.CookieJar()

  await each(cookies, async (cookie) => {
    let parsed = tough.fromJSON({
      key: cookie.name,
fork icon0
star icon0
watch icon1