起こったエラー
DockerでNext.jsとLaravelの環境を構築
getServerSidePropsやgetStaticPropsのメソッドの中でLaravelで作成したapiにアクセスしてデータを取得しようとしたところコネクションエラーが発生した。
export const getServerSideProps = async () => {
const res = await fetch('http://localhost:8080/api/users')
const data = await res.json()
return { props: { data } }
}
このように記述をして全然データ取得が出来ませんでした。
試しにuseEffectの中で同じエンドポイントのhttp://localhost:8080/api/usersにデータを取得しに行ったところ問題なく取得できました。
useEffectの中では出来てなぜ出来ないのか分からず、getServerSidePropsの書き方がおかしいのではないかと思い軽く合計で5〜6時間は葛藤しました。
解決策はgetServerSidePropsやgetStaticPropsの中でデータを取得する場合はlocalhost:8080ではなくて、nginx:80にすることでした。
export const getServerSideProps = async () => {
const res = await fetch('http://nginx:80/api/users')
const data = await res.json()
return { props: { data } }
}
このようにしたら取得できました。
dockerの構成はこんな感じです。
nginx:
container_name: nginx
ports:
- 8080:80
一応解決はできたけど、自分の中でこの現象を完全に理解しきれていないのでもう少し勉強します。
Dockerもちゃんと勉強したい....