Express

suyeonme·2021년 3월 14일
0

Node.js

목록 보기
1/3

Router

The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.

index.js

  • app.use(express.json()): JSON을 object로 변환
// src/index.js
const express = require('express');
const userRouter = require('./routers/user'); // (*)
const taskRouter = require('./routers/task'); // (*)

const app = express();
const port = process.env.PORT | 3000;

app.use(express.json());
app.use(userRouter);  // (*)
app.use(taskRouter); // (*)

app.listen(port, () => {
  console.log('Server is up on ' + port);
});

user.js

  • express.Router안에서 DB의 CRUD를 설정할 수 있다.
// src/routers/user.js
const mongoose = require('mongoose');
const validator = require('validator');

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  email: {
    type: String,
    required: true,
    trim: true,
    validate(value) {
      if (!validator.isEmail(value)) {
        throw Error('Email is invalid!');
      }
    },
  },
  password: {
    type: String,
    required: true,
    trim: true,
    minLength: 7,
  },
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

404 Page

*all match를 의미한다. 따라서 가장 마지막에 위치시켜야한다.(중요!)

// other routes...
app.get('*', (req, res) => {
  res.render('404', {
    title: '404 Page',
    error: 'Page not found',
    name: 'Suyeon',
  });
});
profile
Frontend Engineer.

0개의 댓글