React Express 연동 (React -> Express)

lee-kyu-hwan·2022년 3월 16일
0

React-Express-MySQL

목록 보기
1/2

준비

Node.js 설치

https://nodejs.org/en/

Create React App

npx create-react-app 앱이름
npx create-react-app@latest 앱이름 // 최신

client라는 이름으로 리액트 프로젝트 생성

Express 설치

server 폴더를 만든후 Express & nodemon 설치

npm init
npm install express --save
npm install nodemon --svae
npm install cors
npm install body-parser

--save 종속 항목 목록에 저장

코드 작성

sever.js

const express = require("express");
const app = express();
const port = 4999 // <- 통신할 포트 번호
const cors = require("cors");
const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(bodyParser.json());

app.get("/", (req, res) => {
  res.send("Hello World!"); //홈 페이지에서 Hello World!로 응답:
});

app.post("/text", (req, res) => { //text에서 POST 요청에 응답 
  const text1 = req.body.inText;
  console.log(text1);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

sever 폴더안에 server.js를 만든후 코드 작성

nodemon server.js  //sever 경로 터미널에서 실행

localhost:4999로 접속하면 Hello World!가 나오는 것을 확인

Example.js

import React from "react";

export default class Example extends React.Component {
  state = {
    text: "",
  };

  handlChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  onclick = () => {
    const textbox = {
      inText: this.state.text,
    };
    fetch("http://localhost:4999/text", { //text 주소에서 받을 예정
      method: "post", //통신방법
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(textbox), //textbox라는 객체를 보냄
    });
  };

  render() {
    return (
      <div>
        <input name="text" onChange={this.handlChange}></input>
        <button onClick={this.onclick}>전송</button>
        <h3>{this.state.text}</h3>
      </div>
    );
  }
}

App.js

import React from "react";
import Example3 from "./Example3";

function App() {
  return (
    <div>
      <Example3 />
    </div>
  );
}

export default App;

참고문서

profile
웹, 앱, 그리고 사람들의 마음을 잇는 개발자가 되고 싶습니다!

0개의 댓글