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: