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



Related Posts:

  • NodeJS ExpressJS: Template engines [EX-02] Using template engines with Express Pug (jade), Mustache, EJS [1] Single page application (SPA)  - Nội dung render trên front end  - Không load lại trang  - Tương tác với data dạng Json API [2] Multiple pag… Read More
  • 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', … Read More
  • NodeJS ExpressJS: Nodemon [EX-05] Nodemon Tự động load project https://github.com/remy/nodemon/ Cách 1: Cài đặt trên toàn hệ thống npm install -g nodemon Cách 2: Cài đặt trên môi trường devDependencies npm install --save-dev nodemon <<… Read More
  • 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… Read More
  • NodeJS ExpressJS: Database (Lowdb) [EX-06] Lowdb Cài đặt module npm install lowdb --save Refer: https://github.com/typicode/lowdb /app.js app.js const express = require('express') const app = express() const port = 3000 // lowdb module const low = requir… Read More

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang