What is the correct way to add a cookie with axios.post from nodejs ?

See original GitHub issue

Hello,

I am working on a Node.JS -based mobile app (Expo SDK36, React Native 0.61) and I am using axios (0.19.1) to communicate with a private server.

I am trying to make some POST requests which should include an authorization token as a cookie. So far, I have been able to make requests to the server without a cookie in order to authenticate a user through his credentials. The server correctly responds with a cookie in the header representing the user authorization token for any future requests. I am saving that cookie data in a class field this.user_auth_token. No matter how I try however, it seems like I am unable to add a cookie to a future request to the server. In code:

const myServerInstance = axios.create({
    method: "POST",
    baseURL: "http://my-private-server.abc",
    auth: {
        // the server requires basic authentication before accepting any requests
        username: "my-private-username",
        password: "MY_sup3r_S7R0n6_p@$$w0rd"
    },
    headers: {
        "Content-Type": "application/json"
    }
});

/* somewhere else in the node.js app code */
myServerInstance.post("/login", {
    user_name: "SomeUserName",
    user_password: "Encrypted_p@$$w0rd"
}).then( response => {
    // yey, response received, let's get the token from the cookies in the response
    this.user_auth_token = response.headers["set-cookie"][0].match(/token=(.+);/);
}).catch( error => {
    console.log(":sad-face: an error occurred...", error);
});

Until here, everything is good. I get the token, I have it saved in this.user_auth_token, all good. Now, I’ll try to make a request that needs this token in order to be accepted:

// at this point the value of this.user_auth_token is correctly the authorization token
myServerInstance.post("/load-user-profile", {
    headers: {
        "Content-Type": "application/json",
        Cookie: `token=${this.user_auth_token};`
    }
}).then( response => {
    console.log("USER PROFILE RESPONSE DATA", response.data);
}).catch( error => {
    console.log(":sad-face-again: some error", error.message);
    // the error message is a custom error returned from the server:
    // "Request denied, invalid or missing authorization token"
});

I have tried passing the Cookie as many different types of data including:

  • { token: this.user_auth_token }
  • JSON.stringify({ token: this.user_auth_token })
  • “token=”+this.user_auth_token+“;”
  • “token=abcdefghijklmnopqrstuvwxyz;” (a hard-coded string)

and many other that I may have forgotten. None of the ways I tried made the token cookie arrive on the server. I have tried using the withCredentials parameter, both true and false don’t seem to change anything.

So, how can I add a cookie to the post request that axios does ? What am I doing wrong ?

I have also seen this thread: https://github.com/axios/axios/issues/943 No replies from there helped…

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:11
  • Comments:5

github_iconTop GitHub Comments

29reactions
BernardMarieOnzocommented, Apr 1, 2020

hi you can check this

3reactions
CostachescuCristinelcommented, Jan 21, 2021

The best I could solve this is by creating an axios instance, and reusing the same instance for all further requests. Also, in every request, I make sure to include withCredentials=true and the Cookies="my-cookie; ..." header with the cookies that I want to send (or empty string if none should be sent).

Also, make sure you match the request according to the Access-Control-Allow-Origin header sent back in the server response, otherwise, XHR could discard cookies and other data. Cookies should be allowed if the Access-Control-Allow-Origin is same-origin, but I am not sure what happens if instead is * (any wildcard).

Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js axios request with cookies - Stack Overflow
Having the withCredentials key enabled (set to 'true') should solve your issue. ... withCredentials = true; axios.post(url, body).then(.
Read more >
Handling cookies with axios - Medium
Handling cookies with axios · To stringify the data before sending. I tried both JSON. · Setting {withCredentials: true} while making request.
Read more >
How to Pass Cookies with Fetch or Axios Requests - Sabe.io
If you want to pass cookies with this request, you can do so by passing the credentials option to the fetch request. fetch("http://example.com/ ......
Read more >
Pass cookies with axios or fetch requests - Code with Hugo
Pass cookies with requests in axios. In axios, to enable passing of cookies, we use the withCredentials: true option.
Read more >
axios set cookie not working | The AI Search Engine You Control
If you want to use Cookies with Axios you need to include the withCredentials property. axios.post('ABC.com/Users/Login', form, { withCredentials: true });.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found