C -> Insert -> POST
R - Select -> GET
U - Update -> PUT
D - Delete -> DELETE

Request Type 별로 분리한 방식

 

1. app.js

var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app).listen(80);
var mysql = require('mysql');
console.log("Server is running...")

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({limit: '50mb', extended: false}));
app.use(bodyParser.json({limit: '50mb'}));

var connection = mysql.createConnection({
	host: 'localhost'
	, port: 3308
	, user: 'root'
	, password: '1234'
	, database: 'javascript'
});


app.get('/', function (req, res) {
  res.sendfile("newsList.html");
});
app.get('/newsListPage', function (req, res) {
  res.sendfile("newsList.html");
});
app.get('/newsPostPage', function (req, res) {
  res.sendfile("newsPost.html");
});
app.get('/newsUpdatePage', function (req, res) {
  res.sendfile("newsUpdate.html");
});

app.get('/news', function (req, res) {
	if(req.query.no) {
		var q = `select * from news where no = ${req.query.no}`;
	  connection.query(q,
	    function (err, rows, fields) {
	      if (err) throw err;
	      res.send(rows);
	    }
	  );
	}
	else {
		var q = 'select * from news';
	  connection.query(q,
	    function (err, rows, fields) {
	      if (err) throw err;
	      res.send(rows);
	    }
	  );
	}
});

app.post('/news', function (req, res) {
	var title = req.body.title;
	var content = req.body.content;
	var q = `insert into news (title, content) values ("${title}", "${content}")`
  connection.query(q,
    function (err, rows, fields) {
      if (err) throw err;
      res.send(rows);
    }
  );
});

app.put('/news', function (req, res) {
	var no = req.body.no;
	var title = req.body.title;
	var content = req.body.content;
	var q = `update news set title="${title}", content="${content}" where no = ${no}`
  connection.query(q,
    function (err, rows, fields) {
      if (err) throw err;
      res.send(rows);
    }
  );
});

app.delete('/news', function (req, res) {
	var no = req.body.no;
	var q = `delete from news where no=${no}`;

  connection.query(q,
    function (err, rows, fields) {
      if (err) throw err;
      res.send(rows);
    }
  );
});

 

 

2. newsList.html (http://localhost/)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div id="newsListArea"></div>
    <input type="button" value="글쓰기" id="goToPostBtn">
  </body>

  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript">
    $.ajax({
      url:'/news',
      data:"",
      success:function(res){
        for(var i=0;i<res.length;i++) {
          var news = res[i];
          $("#newsListArea").append(`제목 : ${news.title}
            <input type="button" value="수정" onclick="updateNews(${news.no})">
            <input type="button" value="삭제" onclick="deleteNews(${news.no})">
            <br> 내용 : ${news.content} <br><br>`);
        }
      }
    });

    $("#goToPostBtn").click(function(){
      location.href = "/newsPostPage";
    });

    function updateNews(no) {
      location.href = "/newsUpdatePage?" + no;
    }

    function deleteNews(no) {
      if(confirm("삭제하시겠습니까?")) {
        //삭제
        $.ajax({
          url:'/news',
          type:"DELETE",
          data:{
            no: no
          },
          success:function(res){
            location.href = "/";
          }
        });
      }
    }

  </script>
</html>

 

 

3. newsPost.html (http://localhost/newsPostPage)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <style type="text/css">
      textarea{ resize: none;}
    </style>
    <title></title>
  </head>
  <body>
    <!-- <input type="text" id="title">
    <input type="text" id="content"> -->
    <input type="text" placeholder="기사 제목을 입력하세요." id="title" style="width:500px"><br><br>
    <textarea cols="69" rows="15" placeholder="기사 내용을 입력하세요." id="content"></textarea>
    <input type="button" value="글쓰기" id="postNews">
    <input type="button" value="돌아가기" id="backToListBtn">
  </body>

  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript">
    $.ajax({
      url:'/',
      data:"",
      success:function(res){
      }
    });

    $("#backToListBtn").click(function(){
      location.href = "/";
    });

    $("#postNews").click(function(){
      $.ajax({
        url:'/news',
        type:"POST",
        data:{
          title: $("#title").val(),
          content: $("#content").val(),
        },
        success:function(res){
          alert("글 등록이 완료되었습니다.");
          location.href = "/";
        }
      });
    });

  </script>
</html>

 

 

4. newsUpdate.html (http://localhost/newsUpdatePage)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <style type="text/css">
      textarea{ resize: none;}
    </style>
    <title></title>
  </head>
  <body>
    <!-- <input type="text" id="title">
    <input type="text" id="content"> -->
    <input type="text" placeholder="title" id="title" style="width:500px"><br><br>
    <textarea cols="69" rows="15" placeholder="기사 내용을 입력하세요." id="content"></textarea>
    <input type="button" value="수정하기" id="updateNewsBtn">
    <input type="button" value="돌아가기" id="backToListBtn">
  </body>

  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript">
    var no = location.href.split("?")[1];

    $.ajax({
      url:'/news',
      data:{
        no: no
      },
      success:function(res){
        var news = res[0];
        $("#title").val(news.title);
        $("#content").val(news.content);
      }
    });

    $("#backToListBtn").click(function(){
      location.href = "/";
    });

    $("#updateNewsBtn").click(function(){
      $.ajax({
        url:'/news',
        type:"PUT",
        data:{
          no: no,
          title: $("#title").val(),
          content: $("#content").val(),
        },
        success:function(res){
          alert("글이 수정되었습니다.");
          location.href = "/";
        }
      });
    });

  </script>
</html>

 

 

한계 / 고쳐야할 점
1 ) 제목이나 내용에 ' ' 같이 따옴표가 들어갈 경우 쿼리문을 쏠 때 에러가 발생한다.    ex) 38도 '찜통'... X
2 ) <br>태그 등에 대한 줄나눔 처리가 안 된다.

 

 

 

 

DB

더보기

Database : MySQL / Database Name : javascript / Table Name : news

CREATE TABLE javascript.news (
	`no` INT auto_increment NOT NULL,
	title varchar(100) NULL,
	content varchar(5000) NULL,
	CONSTRAINT news_PK PRIMARY KEY (`no`)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8
COLLATE=utf8_general_ci;

+ Recent posts