Sunday, 21 February 2021

nextjs 4 api response

code linkhttps://github.com/chuanshuoge6/nextjs
api json response

fetch from api

//api/articles/index.js

import {articles} from '../../../data'

export default function handler(req, res){
    res.status(200).json(articles)
}

---------------------
//api/articles/[id].js

import {articles} from '../../../data'

export default function handler({query: {id}}, res){
    const filtered = articles.filter(article => article.id === id)
    
    if(filtered.length > 0){
        res.status(200).json(filtered[0])
    }
    else{
        res.status(404).json({message: ` Aritle with the id of ${id} is not found`})
    }
}

-----------------------------
//data.js

export const articles = [
    {
      id: '1',
      title: 'GitHub introduces dark mode and auto-merge pull request',
      excerpt:
        'GitHub today announced a bunch of new features at its virtual GitHub...',
      body:
        'GitHub today announced a bunch of new features at its virtual GitHub Universe conference including dark mode, auto-merge pull requests, and Enterprise Server 3.0. In the past couple of years, almost all major apps have rolled out a dark theme for its users, so why not GitHub?',
    },
...
----------------
//pages/index.js

import Head from 'next/head'
import ArticleList from '../components/ArticleList'
import {server} from '../config'

export default function Home({articles}) {
  //console.log(articles)
  return (
    <div>
      <Head>
        <title>WebDev Newz</title>
        <meta name='keywors' content='web development'/>
      </Head>

      <ArticleList articles={articles} />
    </div>
  )
}

export const getStaticProps = async () => {
  const res = await fetch(`${server}/api/articles`)
  const articles = await res.json()

  return{
    props:{articles}
  }
}

--------------------
//pages/articles/[id]/index.js

import {useRouter} from 'next/router'
import Link from 'next/link'
import {server} from '../../../config'

const article = ({article}) => {

    return (
    <div>
        <h1>{article.title}</h1>
        <p>{article.body}</p>
        <br/>
        <Link href='/'>Go Back</Link>
    </div>)
}

export const getStaticProps = async (context) =>{
    const res = await fetch(`${server}/api/articles/${context.params.id}`)
    
    const article = await res.json()
    
    return{
        props:{article}
      }
}

export const getStaticPaths = async () =>{
    const res = await fetch(`${server}/api/articles`)
    
    const articles = await res.json()

    const ids = articles.map(article => article.id)
    const paths = ids.map(id => ({params: {id: id.toString()}}))
    
    
    return{
        paths,
        fallback: false
      }
}

export default article

-----------------------
//config/index.js

const dev = process.env.NODE_ENV !== 'production'

export const server = dev ? 'http://localhost:3000' : 'https//yourwebsite.com'

---------------------
reference:

No comments:

Post a Comment