0
0

More than 3 years have passed since last update.

absoluteUrl の使い方 備忘録

Posted at

環境

Node.js v15.3.0
Next.js v10.2.0

やりたいこと

  • fitch で JSON を読み込み
  • 読み込んだデータを画面に表示
  • カレントホスト名はハードコードしたくない

結論

以下の様にコード化する。

//@see : https://www.npmjs.com/package/next-absolute-url
import absoluteUrl from 'next-absolute-url';

export default function Home() {
    // データソースのURL
    const dataURL = '/data.json';

    // データソースの相対URL
    const relativeURL = '.' + dataURL;

    // Get Request のインスタンス化
    // @see: https://developer.mozilla.org/ja/docs/Web/API/Request
    const request = new Request( relativeURL );

    // Request から、プロトコル|インターネットホスト名|オリジンを取得
    // @return {
    //     protocol: string;
    //     host: string;
    //     origin: string;
    //}
    const { origin } = absoluteUrl( request );

    // オリジンとデータソースのURLをくっつける(絶対URL化)
    const url = origin + dataURL;

    // native fitch() を call。
    fitch( url ).then(res => res.json())
    //@TODO: 以下、描画処理
}

参考リンク

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