クイックレスポンス


server.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!");
});

app.post("/text", (req, res) => {//데이터 받는 곳
  const text1 = req.body.inText;
  console.log(text1);
  const sendText = {
    text: "보내기 성공",
  };
  res.send(sendText);
});

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

Example.js

import React from "react";

export default class Example3 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:3001/text", {
      method: "post", //통신방법
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(textbox),
    })
      .then((res) => res.json()) //추가된 부분
      .then((json) => {
        console.log(json);
        this.setState({
          text: json.text,
        });
      });
  };

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

リファレンス


https://wonyoung2257.tistory.com/6?category=805961