29 September 2019

NodeJS ExpressJS: Query parameters [EX-03]

Query parameters 
Query parameters
app.js
const express = require('express')
const app = express()
const port = 3000

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

var users = [{
    id: 'ID291',
    name: 'David Zinn'
}, {
    id: 'ID292',
    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/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}!`))

views/index.pug
index.pug
html
  head
    title= title
  body
    h1= message

    a(href='/users') Users

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

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

ul
    each user in users
        li= user.id + ': ' + user.name

Command: node app.js
Url: http://localhost:3000/users/search?name=David
Kết quả: ID291: David Zinn



0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang