在nodejs中的axios保持cookie

使用了thinkjs框架,其它的环境大同小异,为防止以后会用到,特此记录

const Base = require('./base.js');
const axios = require('axios');
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('axios-cookiejar-support').default;
axiosCookieJarSupport(axios);
module.exports = class extends Base {
  async __before() {
    let that = this;
    //获取已经保存的cookies,如果没有那就直接登录,并且缓存下来
    let cookies = await that.cache('cookie', async() => {
      let newCookieJar = new tough.CookieJar();
      await axios({
        method: 'post', url: '',
        jar: newCookieJar, // tough.CookieJar or boolean
        withCredentials: true, // If true, send cookie stored in jar
        data: {}
      });
      return newCookieJar.toJSON();//使用json的方式保存cookie
    }, {timeout: 2 * 60 * 60 * 1000});
    that.cookieJar = new tough.CookieJar.fromJSON(cookies);//从json里获取cookie并生成新对象
    console.log(cookies);
  }

  async indexAction() {
    let that = this;
    let {data: datatList} = await axios({
      url: '',
      method: 'post',
      jar: that.cookieJar, // tough.CookieJar or boolean
      withCredentials: true,
      data: {}
    });
    console.log(datatList);
  }
};

你可能感兴趣的:(在nodejs中的axios保持cookie)