Example

Using templates

app.set('view engine', 'pug')

Create a Pug template file named index.pug in the views directory with the following content

html
  the head
    title= title
  the body
    h1=message

Create a route to render the index.pug file. If the view engine property is not set, the extension of the view file must be specified

app.get('/', (req, res) => {
  res. render('index', {
    title: 'Hey', message: 'Hello there!'
  })
})

Middleware

function logOriginalUrl (req, res, next) {
  console.log('ReqURL:', req.originalUrl)
  next()
}
function logMethod (req, res, next) {
  console.log('Request Type:', req.method)
  next()
}
const log = [logOriginalUrl, logMethod]
app.get('/user/:id', log,
  (req, res, next)=>{
    res.send('User Info')
  }
)

Routing

const express = require('express')
const app = express()
//Respond to "hello world" when making a GET request to the homepage
app.get('/', (req, res) => {
  res.send('hello world')
})
// GET method routing
app.get('/', (req, res) => {
  res.send('GET request to the homepage')
})
// POST method routing
app.post('/', (req, res) => {
  res.send('POST request to the homepage')
})

app.listen([port[, host[, backlog]]][, callback])

var express = require('express')
var app = express()
app.listen(3000)

app.engine(ext, callback)

var engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)

app.disabled(name)

app.disabled('trust proxy')
// => true
app.enable('trust proxy')
app.disabled('trust proxy')
// => false

app.disable(name)

app.disable('trust proxy')
app.get('trust proxy')
// => false

app.delete

app.delete('/', function (req, res) {
  res.send('DELETE request to homepage')
})

app.all

app.all('/secret', function (req, res, next) {
  console.log('access secret section...')
  next() // Pass control to the next handler
})

res.json([body])

res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })

res. end()

res. end()
res.status(404).end()

End the response process. This method actually comes from the Node core, specifically the response.end() method of http.ServerResponse

Comments