Nodejs 上的 Axios 不会在 PostMan 上保留请求的服务器上的会话 [英] Axios on Nodejs wont retain session on requested server while PostMan does

查看:28
本文介绍了Nodejs 上的 Axios 不会在 PostMan 上保留请求的服务器上的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 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)

更多信息:

这篇关于Nodejs 上的 Axios 不会在 PostMan 上保留请求的服务器上的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆