json-server, axios

suyeon·2022년 1월 14일
1

json-server
json-server는 별도의 서버가 없는 환경에서 프론트엔드 작업을 진행하고자 할 때, 짧은 시간에 REST API 를 구축해주는 라이브러리이다.

사용 방법은 아래와 같다.
1. $ npm i -g json-server // 설치
2. db.json(json 파일명) 파일 만들기
3. $ json-server --watch db.json(json 파일명) --port 9000(사용하려는 포트번호)

그러면, REST API 서버가 열리게 된다. 예를 들어, http://localhost:9000/stores로 들어가면 json 데이터를 확인할 수 있다.

이 과정에서 아래와 같은 오류가 나서 오래 고민했는데, 3000번인 로컬 서버만 실행하고, 9000번 서버는 실행하지 않았기 때문이었다.
// net::ERR_CONNECTION_REFUSED
에디터의 터미널을 두 개 열어, 하나는 로컬로 앱을 실행하고, 하나는 json-server --watch db.json --port 9000로 분리하여 실행하니 오류가 해결되었다.

Axios
Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리다.
1. $ npm i axios
2. import axios from 'axios'
3.

import axios from 'axios';

axios.get('https://localgost:9000/stores')
  .then((Response)=>{console.log(Response.data)})
  .catch((Error)=>{console.log(Error)})

사용방법은 아래와 같다.

import Header from '../components/Header';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Link from 'next/link';

export default function Store() {
  const [stores, setStores] = useState([]);
  useEffect(() => {
    axios.get('http://localhost:9000/stores')
    //.then((data) => console.log(data.data))
    .then(data => {
      setStores(data.data);
    });
  }, []);
  
  return (
    <div>
      <Header></Header>

      <div className="container">
        {stores.map((store) => (
        <div key={store.id} className="item">
          <Link
            href={{
              pathname: '/[id]',
              query: { id: store.id, name: store.name, image: store.image, description: store.description, url: store.url },
            }}>
            <img src={store.thumb}/>
          </Link>
        </div> 
        ))}
      </div>

    </div>
  )}

0개의 댓글

관련 채용 정보