LoginSignup
7
5

More than 1 year has passed since last update.

Node.jsからLINE Notifyを使うメモ (Fetch API利用)

Last updated at Posted at 2022-04-26

Node.js v18のアップデートでFetch APIがフラグなしで使えるようになったよという話題があるのでLINE NotifyのAPIで試してみました。

「Node.js 18」がリリース ~fetch API、Web Streams APIがグローバルスコープで利用可能に

先に実装したコピペ用コード

v18以降ならこのまま実行して動くと思います。

'use strcit';

const BASE_URL = 'https://notify-api.line.me';
const PATH =  '/api/notify';
const LINE_TOKEN = `トークン`;

const params = new URLSearchParams({
    message: 'こんばんわ。Node.js v18 Fetch APIでLINE Notify API を使ってみました。',
});

const config = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${LINE_TOKEN}`
    },
    body: params.toString()
};


const main = async () => {
    const res = await fetch(BASE_URL + PATH, config);
    console.log(res.status);
}

main();

スクリーンショット 2022-04-26 11.02.50.png

問題なく動きました。

書き換えた部分

ちなみに前に書いたaxiosのコードを参考に書き換えてます。

パラメータの指定が少し書きかわってるのはありますが、大体似たような感じです。

axiosだとdataにリクエストデータを詰め込みますが、bodyになっています。

また、これはFetch API話とは違いますが、querystringの箇所も怒られたのでURLSearchParamsを利用するように書き換えました。

Fetch APIのリクエストオプション

MDNのサイトに書いてるものを参考に。

所感

試してないですが、ブラウザ側と同じコードで動きそうですね。

npm i axiosなどを実行しないでできるのは新鮮。

7
5
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
7
5