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