08 October 2019

NodeJS ExpressJS: Post method [EX-04]


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

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

    button create

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

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

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

ul
    each user in users
        li= user.name

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

https://expressjs.com/en/4x/api.html#req.body
Post method
app.js
const express = require('express')
const app = express()
const port = 3000

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

app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

var users = [{
    name: 'David Zinn'
}, {
    name: 'Erwin Rommel'
}]

// 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: users
    })
})

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

// POST create user
app.post('/users/create', function (req, res) {
    users.push(req.body);
    res.redirect('/users');
})

// GET method route
app.get('/users/search', function (req, res) {
    var q = req.query.name;
    var matchUsers = users.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}!`))

Command: node app.js
Kết quả:
<< back | next >>

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang