반응형

개요

 

이번에는 REST API에 대해서 알아보도록 하겠습니다.


설명

 

전체 고객을 불러오는 동작을 구현해 보도록 하겠습니다.

 


server.js

 

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/api/customers',(req,res) => {
    res.send([
        {
            'id' :1,
            'image':'https://placeimg.com/64/64/1',
            'name':'홍길동',
            'birthday':'961222',
            'gender':'남자',
            'job':'학생'
            },
            {
              'id' :2,
              'image':'https://placeimg.com/64/64/2',
              'name':'정성현',
              'birthday':'960402',
              'gender':'남자',
              'job':'인턴' 
            },
            {
            'id' :3,
            'image':'https://placeimg.com/64/64/3',
            'name':'김덕배',
            'birthday':'990821',
            'gender':'남자',
            'job':'장군'
        }
    ]);
});

 


json 파일 형식

 


결과

 

 

이제 터미널 창에 yarn dev라고 타이핑을 하게 된다면 3000 포트는 React 화면이

5000 포트의 api/customers는 위와 같은 창이 나오게 됩니다.

 

그런 다음 client의 package.json 파일에서 아래의 구문을 추가시켜줍니다.

 

이제는 app.js 파일을 수정하여 실제로 API 서버에 접근할 수 있도록 처리하도록 하겠습니다.

React는 보통 비동기적으로 많이 쓰이기 때문에 async - await 구문을 사용했습니다. 서버로부터 JSON 데이터를 받아올 때까지는 테이블에 내용을 출력하지 않다가 데이터를 모두 받아왔을 때 비로소 테이블에 내용을 채우게 됩니다.

 


APP.js

 

import React, { Component } from 'react';
import Customer from './components/Customer'
import './App.css';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableHead from '@material-ui/core/TableHead';
import TableBody from '@material-ui/core/TableBody';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import { withStyles } from '@material-ui/core/styles';

const styles = theme => ({
  root: {
  width: "100%",
  overflowX: "auto"
  },
  table: {
  minWidth: 1080
  }
});

class App extends Component {


  state = {
    customers:""
  }

  componentDidMount() {
    this.callApi()
    .then(res => this.setState({customers:res}))
    .catch(err => console.log(err));
  }

  callApi = async() => {
    const response = await fetch('/api/customers');
    const body = await response.json();
    return body;
  }
  render() {
    const {classes} = this.props;
    return (
      <Paper className={styles("").root}>
        <Table className={styles("").table}>
          <TableHead>
            <TableRow>
              <TableCell>번호</TableCell>
              <TableCell>이미지</TableCell>
              <TableCell>이름</TableCell>
              <TableCell>생년월일</TableCell>
              <TableCell>성별</TableCell>
              <TableCell>직업</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {this.state.customers ? this.state.customers.map(c => {
            return <Customer key={c.id} id={c.id} image={c.image} name={c.name} birthday={c.birthday} gender={c.gender} job={c.job} />
            }) : ''}
          </TableBody>
        </Table>
      </Paper>
    );
  }
}

export default withStyles(styles)(App);

 

state 는 일반적으로 변경이 될 수 있을 때 사용하며 

props는 값이 변경이 될 수 없을때 사용합니다.

componentDidMount()는 모든 Component가 마운트 되었을 때 실행합니다.

따라서 Component가 준비가 되어있으니까 callApi를 통해서 Api를 불러오도록 합니다.

/api/customers 경로의 json을 body에 담아 두도록 하고 

callApi()를 호출 하여 .then함수로 하여금 res에 담겨있도록 합니다.

 

이렇게 하고 실행하면 오류가 발생하지만 이와같은 경우는 Api를 비동기적으로 받아오기 때문에 

기다리느라 오류가 발생했다고 인식이 됩니다. 그래서 

와 같이 기다리는 동안은 빈공백이 출력되도록 합니다.

 

여기서 오류가 발생한다면 F12를 눌러 개발자 모드에서 네트워크가 불러오는 Api의 포트번호를 다시 

확인해 주고 수정해 주면됩니다.

여기서 3000이라고 되어있지만 실제로는 proxy 설정을 통해서 5000번의 포트에서 가져오고 있는 것입니다.

 


api를 가져오는지 확인

 

 


 

반응형

+ Recent posts