Node.js 주니어 개발자 귤 2022. 12. 18. 02:15

"Node.js와 express로 로그인 기능이 없는 나만의 항해 블로그 백엔드 서버 만들기"

 

app.js

const express = require('express');
const app = express();
const port = 3000;

const commentsRouter = require('./routes/comments');
const postsRouter = require('./routes/posts');
const connect = require("./schemas/index");
connect();

app.use(express.json());
app.use("/", [commentsRouter,postsRouter]);

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(port, () => {
  console.log(port, '포트로 서버가 열렸어요!');
});

 

routes

comments.js

 

const express = require("express");
const router = express.Router();

const Posts = require("../schemas/post");
const Comment = require("../schemas/comment");


// 코멘트 조회
router.get("/comments/:_postid", async(req,res) => {
    const {_postid} = req.params;
    console.log(_postid)
    const dbdata = await Comment.find({_postid:_postid}).sort({createdAt: -1})
    console.log(dbdata)
    res.json({data:dbdata});
});

// 코멘트 작성
router.post("/comments/:_postid", async(req,res) => {
    const {_postid} = req.params;
    const { name, password, contents } = req.body;
    await Comment.create({name, password, contents, _postid});

    res.status(200).json({"message": "댓글을 생성하였습니다."})
});

// 코멘트 수정
router.put("/comments/:commentsid", async(req,res) => {
    const {commentsid} = req.params;
    const {password, contents} = req.body
    const [edit] = await Comment.find({ _id: commentsid })
    if (edit.password === password) {
        await Comment.updateOne({ contents });
    } else {
        return res.status(400).json({"message": "비밀번호가 틀렸습니다."});
    };


    res.status(200).json({ "message": "댓글을 수정하였습니다." });
});

// 코멘트 삭제
router.delete("/comments/:commentsid", async(req,res) => {
    const {commentsid} = req.params;
    const {password} = req.body;
    const [del] = await Comment.find({ _id: commentsid });
    if (del.password === password) {
        await Comment.deleteOne({_id:commentsid})
    } else {
        return res.status(400).json({"message": "비밀번호가 틀렸습니다."})
    };

    res.status(200).json({"message": "댓글을 삭제하였습니다."});
});

module.exports = router;

 

posts.js

 

const express = require("express");
const router = express.Router();

const Post = require("../schemas/post")

// 게시물 조회
router.get("/posts", async (req, res) => {
    const dbdata = await Post.find()
    res.json({ data: dbdata })
});

//게시물 상세 보기
router.get("/posts/:postsid", async (req, res) => {
    const { postsid } = req.params;
    const dbdata = await Post.find()
    const [bora] = dbdata.filter((x) => {
        return x["_id"].toString() === postsid;
    }); //테스트
    res.json({ bora });
});

//게시물 쓰기
router.post("/posts", async (req, res) => {
    const { title, name, password, contents } = req.body;
    await Post.create({ title, name, password, contents })

    res.status(200).json({ "message": "게시글을 생성하였습니다." });
});

//게시물 수정
router.put("/posts/:postsid", async (req, res) => {
    const { postsid } = req.params;
    const { title, password, contents } = req.body;
    const [edit] = await Post.find({ _id: postsid })
    if (edit.password === password) {
        await Post.updateOne({ title, contents });
    } else {
        return res.status(400).json({"message": "비밀번호가 틀렸습니다."});
    };


    res.status(200).json({ "message": "게시글을 수정하였습니다." });
});

//게시물 삭제
router.delete("/posts/:postsid", async (req,res) => {
    const { postsid } = req.params;
    const { password } = req.body;
    const [del] = await Post.find({ _id: postsid });
    if (del.password === password) {
        await Post.deleteOne({_id:postsid})
    } else {
        return res.status(400).json({"message": "비밀번호가 틀렸습니다."})
    };

    res.status(200).json({"message": "게시글을 삭제하였습니다."});
});

module.exports = router;

 

schemas

 

comment.js

 

const mongoose = require('mongoose');
const comment = new mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    contents:{
        type: String,
        required: true
    },
    _postid:{
        type: String,
        required:true
    }
},
{
    timestamps: true
});

module.exports = mongoose.model("Comment", comment);

 

index.js

 

const mongoose = require("mongoose");
mongoose.set('strictQuery', false);

const connect = () => {
  mongoose
    .connect("mongodb://127.0.0.1:27017/node")
    .catch(err => console.log(err));
};

mongoose.connection.on("error", err => {
  console.error("몽고디비 연결 에러", err);
});

module.exports = connect;

 

post.js

 

const mongoose = require('mongoose');
const post = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    name:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    contents:{
        type: String,
        required: true
    },
},
{
    timestamps: true
});

module.exports = mongoose.model("Post", post);