[React & NodeJS]공부#3

jeje·2021년 6월 20일
0

React & Node

목록 보기
3/6

날짜 : 21.06.20
참고 강의

[React.js]

0. 기본 틀 구조

1. React router dom

  • react-router-dom 설치
npm install react-router-dom --save
import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}

export default App;
  • npm start run 실행 후 결과화면

  • 0과 같이 생성했던 틀을 기준으로 코드 수정

// 외부 파일 불러오기
import LandingPage from './components/views/LandingPage/LandingPage';
import LoginPage from './components/views/LoginPage/LoginPage';
import RegisterPage from './components/views/RegisterPage/RegisterPage';


function App() {
  return (
    <Router>
      <div>
        <Switch>
    //route별 불러올 페이지 명시
          <Route exact path="/" component={LandingPage} />
          <Route exact path="/login" component={LoginPage} />
          <Route exact path="/register" component={RegisterPage} />

        </Switch>
      </div>
    </Router>
  );
}

1) LandingPage

2) LoginPage

3) RegisterPage

2. Axios

Axios는 ReactJS에서 Request를 보낼 때 사용하게 된다.

  • Axios 설치
npm install axios --save
  • Axios 간단 예시
    [client]-[LandingPage.js]
import React, { useEffect } from 'react';
import axios from 'axios';

function LandingPage() {

    useEffect(() => {
        axios.get('/api/hello')
            .then(response => console.log(response.data))
    }, []);
    return (
        <div>

        </div>
    )
}

export default LandingPage;

[server]-[index.js]에 아래 코드 추가

app.get('/api/hello', (req, res) => res.send('안녕하세요!'))

⚠️⚠️에러 발생⚠️⚠️

LandingPage의 axios.get을 'http://localhost:5000/api/hello' 로 변경 시도

CORS 에러 발생

3. CORS 이슈 및 Proxy 설정

  • proxy 설치
npm install http-proxy-middleware --save
  • [client]-[src]에 [setupProxy.js] 생성
const createProxyMiddleware = require('http-proxy-middleware');

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

--> target은 node의 서버와 동일하게 설정

  • LandingPage.js에서 axios.get('/api/hello')로 재변환
    --> 실행결과

Full Code

Walang Github

Walang Notion

profile
나의 색으로 가득하게

0개의 댓글