9

I am able to do the following on PostMan

1) POST method to login to company server. 2) Make other requests as a logged in user on company server.

I have created a nodejs app to communicate with the company server. I am using axios library to make said communications.

after Logging in to company server, any other calls don't recognize me as an authorized user.

What could be the differences that i could in turn recreate on axios to have that session persistance?

Emad Said
  • 599
  • 2
  • 5
  • 9

1 Answers1

26

In the browser you use withCredentials in axios - this option automatically saves your session between requests. But in node.js this parameter does not work because axios uses the http node.js module instead of XHR.

In node.js, you can use an axios instance for save cookie between requests.

Simplest way is:

Create instance

const BASE_URL = "https://stackoverflow.com";

// Create instance of axios which utilizes BASE_URL
const axiosInstance = axios.create({ baseURL: BASE_URL });

Write createSession function

const createSession = async () => {
  console.log("create session");
  const authParams = {
    username: "username",
    password: "password"
  };
  const resp = await axios.post(BASE_URL, authParams);
  const cookie = resp.headers["set-cookie"][0]; // get cookie from request
  axiosInstance.defaults.headers.Cookie = cookie;   // attach cookie to axiosInstance for future requests
};

And make call with session cookie

// send Post request to https://stackoverflow.com/protected after created session 
createSession().then(() => {
  axiosInstance.post('/protected') // with new cookie
})

Be careful, your authorization method may differ from the presented - in this case you can just change the createSession method. If your session has expired, you can login again directly or using axios.interceptors - I attached a link to gist.

Also you can use cookie-jar with axios (link below)

For more info:

bdotsamir
  • 97
  • 1
  • 6
Artur Khrabrov
  • 743
  • 8
  • 11
  • hello, your solution with ```cokie-jar```deosn't seem to work or I am doing something else wrong. would you wanna look at my question at https://stackoverflow.com/questions/62455037/cant-login-to-linkedin-with-axios – Akil Demir Jun 19 '20 at 09:10