ตัวอย่าง next js get json file

ตัวอย่างโค้ด เราจะอ่านไฟล์ json ใน getStaticProps ไปดูตัวอย่างกัน

ตัวอย่างโค้ดอ่านไฟล์ json ใน getStaticProps()

import fs from 'fs'
import path from 'path'

export async function getStaticProps() {
    const jsonPath = path.join(process.cwd(), 'data.json')
    const jsonData = JSON.parse(fs.readFileSync(jsonPath, 'utf8'))
    return {
        props: {
            jsonData
        }
    }
}

ทางเลือกอื่น อ่านโดยใช้ isomorphic-unfetch ตามตัวอย่าง

import fetch from 'isomorphic-unfetch'

export async function getStaticProps() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
    const jsonData = await res.json()
    return {
        props: {
            jsonData
        }
    }
}


Copyright © 2023 Devcode Code Example - Powered by www.doesystem.com