React & Node.js

React - Nodejs 연결

NWSV 2020. 4. 29. 16:31

이전까지 개발한 프론트엔드와 서로 데이터를 주고 받을수 있는 API역할을 수행하는 Node.JS 구축 후 React와 연결한다.

Client 설정

client > App.js

이전까지 개발한 프론트엔드와 서로 데이터를 주고 받을수 있는 API역할을 수행하는 Node.JS를 구축한다.

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

const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing(3),
    overflowX: "auto"
  },
  Table: {
    minWidth: 1080 //이렇게 해야 1080이하에서 가로스크롤바가 생긴다.
  }
})

class App extends Component {

  state = {
    customers: ""
  }
  componentDidMount() {
    this.callApi()
    .then(res => this.setState({customers: res})) //받은 변수 이름이 res라는 이름으로 바뀜, 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={classes.root}>
        <Table className={classes.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 => { //c에는 customer이다. 예를들어 홍길동, 예준석, 박지영 처럼
              return (
                <Customer
                  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);

Proxy 설정

client는 3000포트이고 server는 5000포트이다. 둘을 연결해 줘야 한다.

client > src > setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware')

module.exports = function(app) {
    app.use(
        '/api',
        createProxyMiddleware({
          target: 'http://localhost:5000',
          changeOrigin: true,
        })
    );
  };

 

Server 설정

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': '12345',
            'gender': '남자',
            'job': '대학생'
        },
        {
            'id': 2,
            'image': 'https://placeimg.com/64/64/4',
            'name': '이순진',
            'birthday': '999999',
            'gender': '남자',
            'job': '대학생'
        },
        {
            'id': 3,
            'image': 'https://placeimg.com/64/64/3',
            'name': '유관순',
            'birthday': '111111',
            'gender': '여자',
            'job': '대학생'
        }  
    ]);
});

app.listen(port, ()=>console.log(`Listening on port ${port}`));