環境
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: 以下、描画処理
}