#Router
Called for any request passed to this router
router. use(function (req, res, next) {
next()
})
will handle any request ending in /events
router. get('/events', (req, res, next) => {
})
#Response
The res object represents the HTTP response sent by the Express application when it receives an HTTP request
app.get('/user/:id', (req, res) => {
res.send('user' + req.params.id)
})
#Request
A req object represents an HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc.
app.get('/user/:id', (req, res) => {
res.send('user' + req.params.id)
})
#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
#res.json([body])
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
#app.all
app.all('/secret', function (req, res, next) {
console.log('access secret section...')
next()
})
#app.delete
app.delete('/', function (req, res) {
res.send('DELETE request to homepage')
})
#app.disable(name)
app.disable('trust proxy')
app.get('trust proxy')
#app.disabled(name)
app.disabled('trust proxy')
app.enable('trust proxy')
app.disabled('trust proxy')
#app.engine(ext, callback)
var engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)
#app.listen([port[, host[, backlog]]][, callback])
var express = require('express')
var app = express()
app.listen(3000)
#Routing
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('hello world')
})
app.get('/', (req, res) => {
res.send('GET request to the homepage')
})
app.post('/', (req, res) => {
res.send('POST request to the homepage')
})
#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')
}
)
#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!'
})
})