79333377

Date: 2025-01-06 14:40:01
Score: 1
Natty:
Report link

Postman is working by default with a cookie jar enabled, the HTTP client you are using, in Node.js, is not.

You can disable the cookie jar, for each request Postman, if you go to settings, scroll down though the settings, and enable Disable cookie jar, and I expect once you do that, the behavior is identical.

How do you enable cookies in Node.js?

You can wire a cookie jar to your HTTP requests in Node.js. There is no native support for this in Node.js.

This is portion of my code (TypeScript), where I enabled a cookie jar , provided by tough-cookie:

import {CookieJar} from "tough-cookie";

export type HttpFormData = { [key: string]: string; }

export interface IHttpClientOptions {
  baseUrl: string,
  timeout: number;
  userAgent: string;
}

export interface IFetchOptions {
    query?: HttpFormData;
    retryLimit?: number;
    body?: string;
    headers?: HeadersInit;
    followRedirects?: boolean;
}

export class HttpClient {

  private cookieJar: CookieJar;

  public constructor(private options: IHttpClientOptions) {
    this.cookieJar = new CookieJar();
  }

  public get(path: string, options?: IFetchOptions): Promise<Response> {
    return this._fetch('get', path, options);
  }

  public post(path: string, options?: IFetchOptions) {
    return this._fetch('post', path, options);
  }

  public postForm(path: string, formData: HttpFormData,  options?: IFetchOptions) {
    const encodedFormData = new URLSearchParams(formData).toString();
    return this._fetch('post', path, {...options, body: encodedFormData, headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
  }

  public postJson(path: string, json: Object,  options?: IFetchOptions) {
    const encodedJson = JSON.stringify(json);
    return this._fetch('post', path, {...options, body: encodedJson, headers: {'Content-Type': 'application/json.'}});
  }

  private async _fetch(method: string, path: string, options?: IFetchOptions): Promise<Response> {

    if (!options) options = {};

    let url = `${this.options.baseUrl}/${path}`;
    if (options.query) {
        url += `?${new URLSearchParams(options.query)}`;
    }

    // Get cookies from Cookie JAR
    const cookies = await this.getCookies();

    const headers: HeadersInit = {
      ...options.headers,
      'Cookie': cookies // Assign cookies to HTTP request
    };

    const response = await fetch(url, {
      method,
      ...options,
      headers,
      body: options.body,
      redirect: options.followRedirects === false ? 'manual' : 'follow'
    });
    await this.registerCookies(response);
    return response;
  }

  private registerCookies(response: Response) {
    const cookie = response.headers.get('set-cookie');
    if (cookie) {
      // Store cookies in cookie-jar
      return this.cookieJar.setCookie(cookie, response.url);
    }
  }

  public getCookies(): Promise<string> {
    return this.cookieJar.getCookieString(this.options.baseUrl); // Get cookies for the request
  }

}
Reasons:
  • Blacklisted phrase (1): How do you
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Theo Borewit