问题
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?
回答1:
On client side you just use withCredentials params in axios - this option automatically save your session between requests. But in node.js enviroment this parameter not work cause axios uses http node.js module instead of XHR.
In node env you can use axios instance for save cookie between requests.
Simplest way is
Create instance
const BASE_URL = "https://stackoverflow.com";
// Init instance of axios which works with 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 cookie
// send Post request to https://stackoverflow.com/protected after create session
createSession().then(() => {
axiosInstance.post('/protected') // with new cookie
})
Be careful, your authorization method may differ from the presented - on this case you can just change the createSession method. If your session is expire, you can login again directly or using axios.interceptors - i attached a link to gist.
Also you can use axios in connect with cookie-jar (link below)
For more info:
- https://github.com/axios/axios#creating-an-instance
- https://github.com/axios/axios#interceptors
- https://gist.github.com/nzvtrk/ebf494441e36200312faf82ce89de9f2
- https://github.com/3846masa/axios-cookiejar-support
来源:https://stackoverflow.com/questions/49482429/axios-on-nodejs-wont-retain-session-on-requested-server-while-postman-does