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?
One of the important capabilities of Axios is its isomorphic nature which means it can run in the browser as well as in server-side Node. js applications with the same codebase.
Axios can be used in both the browser and in a NodeJs environment.
Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.
Axios works by making HTTP requests with NodeJS and XMLHttpRequests on the browser. If the request was successful, you will receive a response with the data requested. If the request failed, you will get an error. You can also intercept the requests and responses and transform or modify them.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With