Node.js & RESTful API - Wiki Project


Posted by pei_______ on 2022-06-24


Express - Routing
Robo 3T


app.js - constant

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/wikiDB");

const articleSchema = new mongoose.Schema({
  title: String,
  content: String
})

const Article = mongoose.model("Article", articleSchema);

Requests Targetting all Articles

////////////////////////////Requests Targetting all Articles

app.route("/articles")

  // 01. /articles [GET] - Fetches all the articles
  .get(function(req, res) {

    Article.find(

      // 1st input:  callback function
      function(err, articles) {

      if (err) {
        res.send(err);
      } else {
        res.send(articles);
      };
    });
  })

  // 02. /articles [POST] - Creates one new article
  .post(function(req, res) {

    const newArticle = new Article({
      title: req.body.title,
      content: req.body.content
    });

    newArticle.save(

      // 1st input:  callback function
      function(err) {

      if (!err) {
        res.send("Successfully added new article.");
      } else {
        res.send(err);
      }
    });
  })

  // 03. /articles [DELETE] - Deletes all the articles
  .delete(function(req, res) {

    Article.deleteMany(

      // 1st input:  callback function
      function(err) {

      if (!err) {
        res.send("Successfully delete all articles.")
      } else {
        res.send(err);
      }
    });
  });

Requests Targetting A Specific Article

/////////////////////////// Requests Targetting A Specific Article

app.route("/articles/:articleTitle")

  // 04. /articles/<title> [GET] - Fetches the articles with <title>
  .get(function(req, res) {

    Article.findOne(

      // 1st input:  condition
      {title: req.params.articleTitle},

      // 2nd input:  callback function
      function(err, foundArticles) {

      if (!foundArticles) {
        res.send("No article matched that title was found.")
      } else {
        res.send(foundArticles);
      }
    })
  })

// 05. /articles/<title> [PUT] - Rewrite entire article with <title>
  .put(function(req, res) {

      Article.replaceOne(

        // 1st input:  condition
        {title: req.params.articleTitle},

        // 2nd input:  update items, *** will delete if empty
        {title: req.body.title,
          content: req.body.content},

        // 3rd input:  callback function
        function(err) {

          if (!err) {
            console.log(req.body.title);
            console.log(req.body.content);
            res.send("Successfully updated the article.");
          } else {
            res.send(err);
          }
        }
      )
  })

// 06. /articles/<title> [PATCH] - Updates partial article with <title>
  .patch(function(req, res) {

    Article.updateOne(

      // 1st input:  condition
      {title: req.params.articleTitle},

      // 2nd input: only update field
      {$set : req.body},

      // 3rd input:  callback function
      function(err) {

        if (!err) {
          res.send("Successfully updated the article.");
        } else {
          res.send(err);
        }
      }
    )
  })

// 07. /articles/<title> [DELETE] - Deletes the article with <title>
  .delete(function(req, res){

    Article.deleteOne(

      // 1st input:  condition
      {title: req.params.articleTitle},

      // 2nd input:  callback function
      function(err) {

        if (!err) {
          res.send("Successfully delete the article.");
        } else {
          res.send(err);
        }
      }
    )
  })

app.js - constant

app.listen(3000, function() {
  console.log("Server started on port 3000");
});









Related Posts

F2E合作社|按鈕元件|Bootstrap 5網頁框架開發入門

F2E合作社|按鈕元件|Bootstrap 5網頁框架開發入門

Return an array of the number smaller than n

Return an array of the number smaller than n

MTR04_0918

MTR04_0918


Comments