본문 바로가기

Project 기록/와글와글(web)

[프로젝트]텍스트 입력후 데이터베이스에 넣기(nodejs,react,mysql사용)

728x90
반응형

영빈이가 

 

오랜만에 오더를 줬다 제작중인 웹에 피드백을 받기위해 

 

불편사항 신고기능을 만들어라고 했다

 

입력받은 내용을 디비에 넣기만 하면 된다 함 해보자

 


 

 

내 핸드폰 아이폰7기준으로 인터페이스를 만들었다 정말 깔끔하고 예쁘다

 

기능을 보자


<Singo_page.js>

 

제출 버튼에 onClick 이벤트를 주고 onSubmit함수를 이용해 데이터를 보낼 예정이다

<button onClick={this.onSubmit}>제출</button>

 

제목을 받는 input 태그와 내용을 받는 textarea 태그에 onChange함수 이벤트를 주었다

<textarea
   name="content"
   placeholder="최대 200자까지 가능해요"
   onChange={this.onChange}
   >
</textarea>

onChange로 인해 input이나 textarea에 입력이 있을 때마다 state값이 초기화 된다

onChange = (e) => {

    this.setState({

      [e.target.name]: e.target.value, // 변화가 있을때마다 state값을 초기화

    });
  };

 

아 state값은 이거다

  this.state = {
      title: false,  //제목
      content: false,  //내용
    };

 

 

이제 데이터를 보낼 onSubmit함수를 보자

  onSubmit = (e) => {
    e.preventDefault();
    const data = {  //state값인 title과 content를 data로 묶는다
      title: this.state.title,
      content: this.state.content, // 현재 id state값을 data.id에 넣는다
    };

    let length = this.state.content;  //길이를 구하기위해

    if (this.state.title == "" || this.state.content == "") { // 내용을 안썼으면 alert발동
      alert("제목이나 내용을 입력해 주세요");
    } else if (length.length >= 200) {  //내용 입력값의 길이가 200자가 넘어가면 alert발동
      alert("200자를 초과 했어요");
    } else {
      fetch("api/Singo", { //서버의 Singo라우터를 찾아간다
        method: "post",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data), // json화 해버리기
      });
      
      alert("제출 되었습니다 감사합니다"); //제출 알림
    }
  };

 

 

<server>

router.post("/Singo", (req, res) => {
  let singo_title = req.body.title;  //받은 데이터 req의 body의 title
  let singo_content = req.body.content; //받은 데이터 req의 body의 content

  console.log(req); //확인용

  let sql = "INSERT INTO singo_table (singo_title,singo_content) VALUES(?, ?);";
  //sql쿼리문이다 singo_table 테이블의 singo_title, singo_content 칼럼에 밸류를 넣는다
  //물음표: 넣을 값
  
  connection.query(sql, [singo_title, singo_content], function (err, result) {  //연결!
    if (err) throw err;
    console.log("1 record inserted");
  });
});

디비에 넣어줬다

 

아 참고로 express mysql body-parser cors 모듈을  사용했다

 

서버페이지 세팅은 

coding-hwije.tistory.com/3?category=83869 요기가 좀 자세한것 같다

 

 

<풀코드> 인데 부끄럽다 이렇게 하는건지 모르겠다

import React from "react";
import "./Singo.css";
import HomeIcon from "@material-ui/icons/Home";

class Singo extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      title: false,
      content: false,
    };
  }

  home = (e) => {
    window.location.replace("/main");
  };

  onChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value, // input 태그에 연결돼 있는 친군데
    }); // 입력 시 이름에 맞는 state 값이 초기화 된다
    console.log(this.state.title + this.state.content);
  };

  onSubmit = (e) => {
    e.preventDefault();
    const data = {
      title: this.state.title,
      content: this.state.content, 
    };

    let length = this.state.content;

    if (this.state.title == "" || this.state.content == "") {
      alert("제목이나 내용을 입력해 주세요");
    } else if (length.length >= 200) {
      alert("200자를 초과 했어요");
    } else {
      fetch("api/Singo", {
        method: "post",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data), // json화 해버리기
      });

      alert("제출 되었습니다 감사합니다");
    }
  };

  render() {
    return (
      <div className="Singo_page">
        <header>불편사항신고</header>
        <body className="Singo_body">
          <span>
            {" "}
            노력하는 창대 학생 개발팀이 되겠습니다
            <br /> 여러분의 신고에 끊임없는 피드백 수정이 <br />
            이루어질 예정입니다 감사합니다
          </span>
          <article>
            <div className="Singo_article">
              <form>
                <div className="first_input">
                  <span>제목</span>
                  <input
                    type="text"
                    name="title"
                    placeholder="살살써주세요"
                    onChange={this.onChange}
                  ></input>
                </div>

                <div className="second_input">
                  <div>내용</div>
                  <div>
                    <textarea
                      name="content"
                      placeholder="최대 200자까지 가능해요"
                      onChange={this.onChange}
                    ></textarea>
                  </div>
                </div>
              </form>
            </div>
          </article>
        </body>
        <footer>
          <button onClick={this.onSubmit}>제출</button>

          <HomeIcon
            className="Home_footer"
            onClick={this.home}
            style={{ fontSize: 50 }}
          />
        </footer>
      </div>
    );
  }
}

export default Singo;

 

<server>

const express = require("express");
const mysql = require("mysql");
const router = express.Router();
var http = require("http").createServer(router);
const io = require("socket.io")(http);

// nodemailer 모듈 요청
const nodemailer = require("nodemailer");
const { light } = require("@material-ui/core/styles/createPalette");
const { futimes } = require("fs");
//mysql연결
var connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "-------",
  database: "wagle",
});


router.post("/Singo", (req, res) => {
  let singo_title = req.body.title;
  let singo_content = req.body.content;

  console.log(req);

  let sql = "INSERT INTO singo_table (singo_title,singo_content) VALUES(?, ?);";

  connection.query(sql, [singo_title, singo_content], function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
  });
});

module.exports = router;

결과: 아무내용도 안썼을때

 

 

 

200자를 초과 했을 때 :

 

정상적인 입력:

 

 

 

디비에 잘 들어온 모습이다

 

실험한다고 빈 데이터를 몇번 보냈던건 무시하고 잘 들어가 있다

 

 

나이스

 

반응형