NEXT.JS_4.1 API 패칭, getServerSideProps & getStaticProps

Eunsu·2021년 12월 9일

4.1 을 먼저 작성하고 나니 이해가 더 잘된다. api/events 서버에서 서버 요청에 대한 status와 method에 대해 조건을 걸어보자!

우선 data.json으로 임의의 데이터 저장을 완료 함.

🎉 DJ- Project 4

🚀 1. api 파일로 데이터 조건 걸기

◻ api/events/index.js

//api/events/index.js
const {events}= require("./data.json");
export default function handler(res,req){
	if(req.method === "GET"){
    	res.status(200).json(events) //get이면 응답상태 200으로 바꾸고, json형식으로 events 가져옴.
    	} else{
        res.setHeader('Allow',["GET"]) // 아니면 rest get으로 바꿈
        res.status(405).json({message: `Method ${req.method} is not allowed`}) // 405로 상태 바꾸고 오류 메세지 생성 
        }
}

◻ api/events/[slug].js

//api/events/[slug].js
const {events}= require("./data.json");
export default function handler(req,res){
	const evt= events.filter(evt => evt.slug === req.query.slug) //필터 돌려서 응답요청받은 slug와 일치하는 slug 찾기
    if(req.method === "GET"){res.status(200).json(evt)}
    else{res.setHeader('Allow',["GET"]);res.status(405).json({message:`Method ${req.method} is not allowed`})}
}

🚀 2. HomePage에서 props 가져오기

props를 가져오는 방식에는 getServerSideProps & getStaticProps가 있다.

✔ getServerSideProps

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
  return { props: { } }
}
  • Fetch data on each request. pre-render for Server-side Rendering
  • 페이지에서 async로 호출 된 함수를 내보내는 경우 getServerSideProps을 사용한다. Next.js는 에서 반환된 데이터를 사용하여 각 요청에서 이 페이지를 미리 렌더링한다.
  • 빌드와 상관없이, 매 요청마다 데이터를 서버로부터 가져온다.

❓ 언제사용하는지?

  • 미리 외부로부터 데이터를 요청하여 페이지에 렌더링이 필요할 경우에 사용한다.
  • 단, 페이지 컴포넌트에 접근 할떄마다 서버에서 항상 실행되기 때문에 속도가 느리고 추가 구성 없이는 데이터를 파싱 할 수 없다.

✔ getStaticProps

export async function getStaticProps() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()
  return {
    props: {
      posts,
    },
  }
}
  • Fetch data at build time, pre-render for Static Generation
  • "빌드 시에 딱 한 번"만 호출되고, 바로 static file로 빌드된다. 따라서, 이후 수정이 불가능하고, SSG (Static Site Generation) 개념입니다.
  • 호출 시 마다 데이터 패칭을 하지 않기 때문에 성능면에서 좋다.

❓ 언제사용하는지?

  • 변하지 않는 공개적인 캐시 데이터를 가져올 필요가 있을 때
  • SEO를 필요로 하는 웹사이트이며, 정적 페이지 배포가 필요할 때

◻ pages/index.js

◾ config/index.js 생성해서 api_url 설정

export const API_URL =
  process.env.NEXT_PUBLIC_API_URL || `http://localhost:3000`;
//pages/index.js
import {API_URL} from "@/config/index"
{..생략}
export async function getStaticProps(){
	const res= await fetch(`${API_URL}/api/events`);
    const events= await res.json();
    return {
    	props:{events}
    }
}

HomePage 함수에서 props로 받기

//pages/index.js
export default HomePage({events}){
console.log(events);
	return <div>This is Home Page</div>
}

잘 들어와 있음.

profile
function = (Develope) => 'Hello World'

0개의 댓글