12 October 2019

NodeJS ExpressJS: Router [EX-08]

Router
db
/db/index.js
index.js
module.exports = {
    lowDB: require('./lowdb')
}

/db/lowdb.js
lowdb.js
// lowdb module
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
// Set some defaults (required if your JSON file is empty)
db.defaults({ users: []})
.write()

module.exports = db;

Router
/routes/index.js
index.js
module.exports = {
    user: require('./user.route')
}

/routes/user.route.js
user.route.js
const express = require('express')
const router = express()

const db = require('../db/index').lowDB;
var ids = require('short-id');

// GET method route
router.get('/', function (req, res) {
    res.render('users/index', {
        users: db.get('users').value()
    })
})

// GET method route
router.get('/create', function (req, res) {
    res.render('users/create')
})

// GET by id
router.get('/:id', function (req, res) {
    var id = req.params.id;
    res.render('users/view', {
        user:  db.get('users').find({ id: id }).value()
    })
})

// POST create user
router.post('/create', function (req, res) {
    // Add a post
    req.body.id = ids.generate(); 
    db.get('users').push(req.body).write()
    res.redirect('/users');
})

// GET method route
router.get('/search/name', function (req, res) {
    var q = req.query.name;
    var matchUsers = db.get('users').value().filter(f => f.name.toLocaleLowerCase().indexOf(q.toLocaleLowerCase()) !== -1);
    res.render('users/index', {
        users: matchUsers
    })
})

module.exports = router;

Views
/views/index.pug
index.pug
html
  head
    title= title
  body
    h1= message
    a(href='/users') Users

/views/users/index.pug
index.pug
h1 User

a(href='/users/create') Create user

form(action = "/users/search/name", method="GET")
    input(type="text", name="name", autocomplete="off")
    button Search

ul
    each user in users
        li
            span= user.name
            span  
            a(href='users/'+ user.id) View

/views/users/create.pug
create.pug
h1 Create user

form(action="/users/create", method="POST")
    label Name
    input(name="name", type="text", autocomplete="off")

    button create

/views/users/view.pug
view.pug
h1 View User

p
    b Name
    span= user.name

App
/app.js
app.js
const express = require('express')
const app = express()
const port = 3000

const userRoute = require('./routes').user;

app.set('view engine', 'pug')
app.set('views', './views');

// https://expressjs.com/en/4x/api.html#req.body
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

// GET method route
app.get('/', function (req, res) {
    res.render('index', {
        title: 'Hey',
        message: "ExpressJS"
    })
})

app.use('/users', userRoute);

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

/package.json
package.json
{
  "name": "example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "lowdb": "^1.0.0",
    "pug": "^2.0.4",
    "short-id": "0.1.0-1"
  },
  "devDependencies": {
    "nodemon": "^1.19.3"
  }
}
Command: npm start

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang