View
Cài đặt module render id tự độnghttps://www.npmjs.com/package/short-id
npm i short-id --save
/app.js
app.js
const express = require('express') const app = express() const port = 3000 // 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() var ids = require('short-id'); 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" }) }) // GET method route app.get('/users', function (req, res) { res.render('users/index', { users: db.get('users').value() }) }) // GET method route app.get('/users/create', function (req, res) { res.render('users/create') }) // GET by id - View user app.get('/users/:id', function (req, res) { var id = req.params.id; res.render('users/view', { user: db.get('users').find({ id: id }).value() }) }) // POST create user app.post('/users/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 app.get('/users/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 }) }) app.listen(port, () => console.log(`Example app listening on port ${port}!`))
users/view.pug
view.pug
h1 View User p b Name span= user.name
Command: npm start
0 nhận xét:
Post a Comment