Node.js Crash Course(8~10)

Coaspe·2021년 3월 17일
0

Node.js Crash Course

목록 보기
2/3
post-thumbnail

➰ What is Middleware?

Code which runs (on the server, top to bottom) between getting a request and sending a response

➰ 3rd party Middleware(morgan)

🔨 Modify 📃 app.js

const express = require("express");
const morgan = require("morgan");
const app = express();

// register view engine
// set ejs view engine
// ejs automaticly checks views folder
app.set("view engine", "ejs");
// app.set('views', 'myviews');

app.listen(3000);

// middleware & static files
app.use(express.static("public"));
app.use(morgan("dev"));

// app.use((req, res, next) => {
//   console.log('new request made:');
//   console.log('host: ', req.hostname);
//   console.log('path: ', req.path);
//   console.log('method: ', req.method);
//   next();
// })
// 이렇게 해놓으면 미들웨어가 다음으로 어디에 가야할지 모른다.
// next()를 사용해야한다.

app.get("/", (req, res) => {
  const blogs = [
    { title: "asdfsdf", snippet: "slekfjselkfj" },
    { title: "sdfsfsef", snippet: "sefseafsdf" },
    { title: "wefsef", snippet: "sdfsefasefse" },
  ];
  res.render("index", { title: "Home", blogs });
});

app.get("/about", (req, res) => {
  res.render("about", { title: "About" });
});

app.get("/blogs/create", (req, res) => {
  res.render("create", { title: "Create a new Blog" });
});

app.use((req, res) => {
  res.status(404).render("404", { title: "404" });
});

➰ Use MongoDB

collection of collection(documents)

📝 Create 📃 blog.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const blogSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    snippet: {
      type: String,
      required: true,
    },
    body: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
); // automatically generates time stamps for us on our blog documents
// Schema is structure of our documents and the model is the thing that surrounds schema and then provides us with an interface by which to communicate with a database collection for that document type

const Blog = mongoose.model("Blog", blogSchema); // mongoose.model(name,) base this name find collection
module.exports = Blog;
profile
https://github.com/Coaspe

0개의 댓글