Authentication POST is successful in the 'request' module but encounters issues with 'node-fetch'

I've encountered an issue with the authentication process when transitioning from the deprecated 'request' module to the 'node-fetch' module. While the authentication request functions as intended with 'request', it fails to return the necessary 'authentication token' cookie with 'node-fetch'.

Below is the code that successfully retrieves the cookies using 'request'

 // Working code with 'request'
var callback1 = function(err, httpResponse, body){
    console.log("Correctly prints all the cookies we want: ");
    console.log(httpResponse.headers["set-cookie"]);
    if (err){console.log("here it is!"); throw err;}
    else {
      //do more with response
    }
};
var callback0 = function(err, httpResponse0, body){
    console.log("Check that sent cookies are identical, from request:");
    console.log(httpResponse0.headers["set-cookie"][0].substr(0,httpResponse0.headers["set-cookie"][0].indexOf(";")));
    if (err){throw err;}
    else {
        // Additional logic here
    }
};
var options0 = {
    // Request options for 'request'
};
request(options0, callback0);

And here is the code with 'node-fetch' that fails to return the auth_token cookie correctly:

 // Code with 'node-fetch'
const fetchOptions0 = {
    // Fetch options for 'node-fetch'
};
fetch(urlString0, fetchOptions0)
.then(res0 => {
    console.log("Check that sent cookies are identical, from fetch:");
    console.log(res0.headers.raw()['set-cookie'][0].substr(0, res0.headers.raw()['set-cookie'][0].indexOf(";")));
    const FormData = require('form-data');
    const myForm = new FormData();
    myForm.append('email', myEmail);
    myForm.append('password', myPassword);
    var fetchOptions1 = {
        // Fetch options for POST request
    };
    fetch(urlString1, fetchOptions1)
    .then(res1=> {console.log("Incorrect cookie, missing auth:"); console.log(res1.headers.raw()['set-cookie']);});
});

I have attempted to use JSON.stringify for the form data based on suggestions from this answer, but it did not resolve the issue.

Answer №1

There exists

a form with fields: {email: myEmail, password: myPassword}

within the request segment of the code. It specifies

application/x-www-form-urlencoded

Refer to https://www.npmjs.com/package/request#applicationx-www-form-urlencoded-url-encoded-forms)

However, there is

a body: myForm

in the fetch portion of the code. This is set to multipart/form-data
Refer to:

  1. first sentence of https://www.npmjs.com/package/form-data
  2. https://www.npmjs.com/package/request#multipartform-data-multipart-form-uploads
  3. https://www.npmjs.com/package/node-fetch#post-with-form-data-detect-multipart

Despite this,

'Content-Type': "application/x-www-form-urlencoded"

remains consistent in the fetch component

If your API endpoint does not support multipart/form-data, it might be advisable to switch from using FormData to URLSearchParams.
Refer to https://www.npmjs.com/package/node-fetch#post-with-form-parameters

Answer №2

If you want to include an

application/x-www-form-urlencoded
payload in the body of your request, simply create a URLSearchParams object

const params = new URLSearchParams();
params.append("username", myUsername);
params.append("password", myPassword);

fetch(apiEndpoint, {
  headers: {
    // your headers
    // do not specify content-length and content-type as node-fetch
    // will manage them for you
  },
  body: params
}).then(response => {
  console.log(response.headers.raw());
})

It appears that in your scenario, you're utilizing FormData, which leads to node-fetch setting multipart/formdata as the header's content-type.

Furthermore, make sure to verify the code in your authorization server to ensure it sends the set-cookie headers correctly.

Tested with:

  • node-fetch v2.6.0
  • nodejs v12.14.0

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent users from copying and pasting text or right-clicking on the website

I have been struggling to completely disable the ability for users to copy and paste or select text on my website across all devices. After much searching, I came across a solution that I implemented on my site. Below the <body> tag, I inserted the ...

The onWrite cloud function does not activate upon the creation of a new document

I have a collection called 'Users' that stores documents with user objects as well as a sub-collection named 'Notifications'. When a new notification is generated for a user, a corresponding document is created in the 'Notification ...

ngClass binding fails to update when using directives to communicate

I am looking to combine two directives in a nested structure. The 'inner directive' includes an ng-class attribute that is bound to a function taking parameters from both inner and outer scopes, and returning a Boolean value. This is the HTML co ...

The react-key-index demonstration isn't functioning properly

Looking to utilize the react-key-index extension for generating unique ids, I attempted to follow their sample example. However, despite my efforts, I keep encountering the same error: TypeError: Hashids is not a constructor Source Link: react-key-inde ...

Data retrieval is currently not functioning, as React is not displaying any error messages

One of the components in my app is as follows: import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { compose } from 'redux'; import { translate ...

Utilizing function arguments in ReactJS

Currently, I am in the process of learning ReactJs and have an inquiry about the code snippet below. Would someone be able to clarify the functionality of the removeTour code and why the id parameter is being used within the function? const removeTour = (i ...

Creating and inserting multiple objects into a table in Sails JS while bypassing any existing rows

Is there a way to insert an array of objects into a table while avoiding duplicate rows? I have a model defined as follows: //Test.js module.exports={ tableName:'test', connection: 'mysqlServer', attributes:{ id:{ type: ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Issues may arise in TypeScript when you are working with an array of objects along with other properties within a type

I am encountering an issue with an object structure similar to the one below: let Obj = { ['0'] : { mode: 'x' }, getMode: () => 'x' } The problem arises when I attempt to create a type definition as shown here: type Obj = ...

Troubleshooting the issue with default useAsDefault routing in Angular 2

I have implemented Angular 2 for routing and Node for local hosting. However, I encountered an issue where using 'useAsDefault:true' for my route caused the nav bar links to stop functioning properly. The URL would redirect to http://localhost/ ...

Is it possible to use a JQuery function after a page redirect has occurred

Take a look at this interesting fiddle! View the Fiddle I am interested in creating links that scroll to different sections of content areas on my site, similar to the footer links in the example. I have been suggested to use Anglers routing system, but ...

Using JavaScript (without jQuery), take away the CSS class from an element

Seeking assistance from experts on the process of removing a class from an element solely using JavaScript. Kindly refrain from suggesting solutions involving jQuery as I am unable to utilize it, and have little knowledge about its functionalities. ...

Have you ever wondered why the expression `Number(new Boolean(false))` always returns `0

In the case of Boolean(new Boolean(...)) === true, it is because new Boolean(...) is treated as an object. However, why does Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Instead of resulting in NaN. Wh ...

Is it possible to customize the CSS styles of a jQuery UI modal dialog box?

Having trouble with my CSS styles not applying to a dialog modal added to my website using jQuery UI, even when using '!important'. I suspect that the predefined jQuery or UI CSS styles from a CDN link are preventing me from overriding them. The ...

Addressing security issues identified by npm audit

I am working on resolving 3 vulnerabilities that were identified by running npm audit, and it appears that the issues cannot be automatically fixed using npm audit fix. ❯ npm audit fix npm WARN audit fix <a href="/cdn-cgi/l/email-protection" class="__ ...

Which is better: Array of Objects or Nested Object structures?

I have a simple programming query that I'm hoping you can help clarify. Currently, I am dealing with numerous objects and I am contemplating whether it's more efficient to search for content within an array of objects or within a nested object s ...

Alpinejs Mega Menu Issue: Hover Functionality Glitchy

I'm working on a complex Mega Menu project that is activated upon hovering, using the powerful combination of Tailwind CSS and Alpinejs. The functionality is mostly there, but I've encountered some bugs along the way. Despite my attempts to impl ...

Is it necessary to save the details of a specific position in local storage when sliding?

Currently, I am in the process of replicating a webpage design from . I have written the code for the functionality where images and phrases change on every slide. There are three different phrases and images that are being displayed, and my goal is to sto ...

Saving game data from local storage to populate the player leaderboard

I have successfully developed a game in which users can play and their scores are stored locally. However, I am facing a challenge in figuring out how to showcase the scores of all users in a table on the Rankings page. Player Ranking Page <?php inclu ...

Exploring the filtering capabilities of Firebase using Vue

I am currently trying to enhance the search functionality in my firebase database to enable users to easily locate the product they are looking for. My current approach involves matching the search query, stored in this.searchText, with the product titles ...