LoginSignup
1
0

More than 5 years have passed since last update.

CloudflareのキャッシュクリアをNode.jsから行うメモ

Last updated at Posted at 2019-02-14

Cloudflareのキャッシュが強いのでキャッシュクリアしたいときがあります。
axiosを使ってAPIを叩いてみましょう。

ちゃんとした手順はこちら(CloudflareのAPIをNode.js+GitLab CIから実行してキャッシュクリアしてみよう)で紹介してます。

npm i axios
'use strict';

if(!process.env.YOUREMAIL || !process.env.APIKEY || !process.env.PURGE_TARGET){
    console.log('環境変数が足りません');
    return;
}

const YOUREMAIL = process.env.YOUREMAIL; //Cloudflareに登録してるメールアドレス
const APIKEY = process.env.APIKEY; //CloudflareのAPI KEY
const PURGE_TARGETS = [process.env.PURGE_TARGET]; //消す対象ページ

const axiosBase = require('axios');
const axios = axiosBase.create({
    baseURL: `https://api.cloudflare.com/client/v4/zones`,
    headers: {
        'Content-Type': 'application/json',
        'X-Auth-Key': APIKEY,
        'X-Auth-Email': YOUREMAIL
    }
})

const main = async() => {
    try {
        //STEP1. ZoneIDの取得
        let res = await axios.get('/');
        const zoneid = res.data.result[0].id;

        //STEP2. キャッシュ削除
        res = await axios.delete(`/${zoneid}/purge_cache`,{
            data: {
                files: PURGE_TARGETS
            }
        });
        console.log(res.data);
    } catch (error) {
        console.log(error.response.data)
    }

}

main();
1
0
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
1
0