25
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AxiosでCookieを自動処理する

Last updated at Posted at 2019-06-30

※環境はNode.js 12.xです

withCredentials: true

色んなサイトに書いてある方法。

const Axios = require('axios');

let client = Axios.create({ withCredentials: true });

const response1 = client.get('https://example.com/set_cookie');
console.log(response1.headers['set-cookie']); // [ 'PHPSESSID=pbjscl1plduu6npqeemep58550' ]

const response2 = client.get('https://example.com/check_cookie');
console.log(response2.indexOf('Cookie') != -1); // false

ところがこの方法ではうまく行かなかった。

axios-cookiejar-support

CookieJarと呼ばれるCookie処理バックエンドを組み込む方法。
まずはプラグインをインストールする。

npm install axios-cookiejar-support

そして実際にリクエストしてみる。

const Axios = require('axios').default;
const AxiosCookiejarSupport = require('axios-cookiejar-support').default;

// Axiosにプラグイン注入
AxiosCookiejarSupport(Axios);

let client = Axios.create({
    jar: true, // cookiejarを有効化する
    withCredentials: true, // 依然として必要
 });

const response1 = client.get('https://example.com/set_cookie');
console.log(response1.headers['set-cookie']); // [ 'PHPSESSID=pbjscl1plduu6npqeemep58550' ]

const response2 = client.get('https://example.com/check_cookie');
console.log(response2.indexOf('Cookie') != -1); // true

うまく行ったらしい。
詳しい使い方はaxios-cookiejar-supportを参照。

25
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?