Nodejs 上的 Axios 不会在请求的服务器上保留会话,而 PostMan 会保留会在、器上、Nodejs、Axios

2023-09-08 08:51:34 作者:゛农村范er

我可以在 PostMan 上执行以下操作

I am able to do the following on PostMan

1) POST 方法登录公司服务器.2) 在公司服务器上以登录用户的身份发出其他请求.

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

我创建了一个 nodejs 应用程序来与公司服务器通信.我正在使用 axios 库进行上述通信.

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.

我可以反过来在 axios 上重新创建以获得该会话持久性的差异是什么?

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

推荐答案

在浏览器中,您在 axios 中使用 withCredentials - 此选项会自动保存请求之间的会话.但是在 node.js 中这个参数不起作用,因为 axios 使用的是 http node.js 模块而不是 XHR.

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.

在 node.js 中,您可以使用 axios 实例在请求之间保存 cookie.

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

最简单的方法是:

创建实例

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

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

编写createSession函数

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
};

并使用会话 cookie 拨打电话

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

请注意,您的授权方法可能与提供的不同 - 在这种情况下,您只需更改 createSession 方法.如果您的会话已过期,您可以直接再次登录或使用 axios.interceptors - 我附上了 gist 的链接.

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.

您也可以将 cookie-jar 与 axios 一起使用(链接如下)

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

更多信息:

https://github.com/axios/axios#creating-an-instancehttps://github.com/axios/axios#interceptorshttps://gist.github.com/nzvtrk/ebf494441e36200312faf82ce89de9f2https://github.com/3846masa/axios-cookiejar-support