A quick reference cheatsheet for Express, a flexible and streamlined web framework for Node.js.
"Create project, add package.json configuration $ mkdir myapp # create directory $ cd myapp # enter the directory $ npm init -y # Initialize a configuration Install dependencies $ npm install express Entry file index.js add code: const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => { res. send('Hello World!') }) app. listen(port, () => { console.log(`Listening port on ${port}`) }) Run the application using the following command $ node index.js
Usage: express [options] [dir]
Options:
-h, --help output usage information
--version output version number
-e, --ejs add ejs engine support
--hbs add hbs engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view No view engine generated
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (default jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (default css)
--git add .gitignore
-f, --force force non-empty directories
Create a myapp project
$ express --view=pug myapp
# run the application
$ DEBUG=myapp:*npm start
express.json() β #
express.raw() β #
express.Router() β #
express.static() β #
express.text() β #
express.urlencoded() β #
router.all() β #
router.METHOD() β #
router.param() β #
router.route() β #
router.use() β #
var express = require('express')
var app = express()
console.dir(app.locals.title)
//=> 'My App'
console.dir(app.locals.email)
//=> '[emailΒ protected]'
app.locals β Local variables in the application #
app.mountpath β Path pattern for mounting sub-apps #
mount β The child application is mounted on the parent application, and the event is triggered on the child application #
app.all() β #
app.delete() β #
app.disable() β #
app.disabled() β #
app.enable() β #
app.enabled() β #
app.engine() β #
app.get(name) β #
app.get(path, callback) β #
app.listen() β #
app.METHOD() β #
app.param() β #
app.path() β #
app.post() β #
app.put() β #
app.render() β #
app.route() β #
app.set() β #
app.use() β #
req.app β #
req.baseUrl β #
req.body β #
req.cookies β #
req.fresh β #
req.hostname β #
req.ip β #
req.ips β #
req.method β #
req.originalUrl β #
req.params β #
req.path β #
req.protocol β #
req.query β #
req.route β #
req.secure β #
req.signedCookies β #
req.stale β #
req.subdomains β #
req.xhr β #
req.accepts() β #
req.acceptsCharsets() β #
req.acceptsEncodings() β #
req.acceptsLanguages() β #
req.get() β Get HTTP request header fields #
req.is() β #
req.param() β #
req.range() β #
app.get('/', function (req, res) {
console.dir(res.headersSent) //false
res.send('OK')
console.dir(res.headersSent) //true
})
res.app β #
res.headersSent β #
res.locals β #
res.append() β #
res.attachment() β #
res.cookie() β #
res.clearCookie() β #
res.download() β Prompt for files to download #
res.end() β end the response process #
res.format() β #
res.get() β #
res.json() β Send JSON response #
res.jsonp() β Send a response with JSONP support #
res.links() β #
res.location() β #
res.redirect() β Redirect request #
res.render() β render view template #
res.send() β Send various types of responses #
res.sendFile() β Send a file as an octet stream #
res.sendStatus() β #
res.set() β #
res.status() β #
res.type() β #
res.vary() β #
Called for any request passed to this router
router. use(function (req, res, next) {
//.. some logic here .. like any other middleware
next()
})
will handle any request ending in /events
//depends on where the router "use()"
router. get('/events', (req, res, next) => {
//..
})
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)
})
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.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(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
app.all('/secret', function (req, res, next) {
console.log('access secret section...')
next() // Pass control to the next handler
})
app.delete('/', function (req, res) {
res.send('DELETE request to homepage')
})
app.disable('trust proxy')
app.get('trust proxy')
// => false
app.disabled('trust proxy')
// => true
app.enable('trust proxy')
app.disabled('trust proxy')
// => false
var engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)
var express = require('express')
var app = express()
app.listen(3000)
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')
})
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')
}
)
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!'
})
})