The Pragmatic Ball boy

iOSを中心にやってる万年球拾いの老害エンジニアメモ

Fetch APIを使ってRailsのAPIを叩く

JavaScript(es2015)でFetch APIを使ってRailsAPIを呼ぶときの方法。

ポイントとしては、'credentials: same-origin'をつけることと、 CSRFを有効にしている場合はheaderにX-CSRF-Tokenをつける点です。

    const getCsrfToken = () => {
        const metas = document.getElementsByTagName('meta');
        for (let meta of metas) {
            if (meta.getAttribute('name') === 'csrf-token') {
                console.log(meta.getAttribute('content'));
                return meta.getAttribute('content');
            }
        }
        return '';
    }

    const postFoo = () => {
        return fetch('/api/foo', {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': getCsrfToken()
            },
            body: JSON.stringify({
                bar: "bar",
            })
        }).then((response) => {
            if (response.status >= 200 && response.status < 300) {
                return response.json();
            } else {
                const error = new Error(response.statusText);
                throw error;
            }
        });
    }