npm init -y
package.json
and package-lock.json
in the root of your project.npm install express@^4.0.0
package.json
file will now list Express as a dependency:{ "name": "my-project-folder-name", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1" } }
app.js
and open in your code editorrequire
directive to import the express
model and assign it to a variable named express
.const express = require('express');
express
function call to a variable named app
:const app = express();
app
variable holds a reference to an Express Application ( app
) object. You'll call methods on the app
object as you build out your web application.app.METHOD(PATH, HANDLER)
app
is an instance of express.METHOD
is an HTTP request method, in lowercase.PATH
is a path on the server.HANDLER
is the function executed when the route is matched.
A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
GET
and POST
are two of the most commonly used HTTP methods, followed by PUT
and DELETE
.get()
app.get('/', function (req, res) => { res.send('Hello from Express!'); });
post()
app.post('/', function (req, res) { res.send('Got a POST request') })
put()
app.put('/user', function (req, res) { res.send('Got a PUT request at /user') })
delete()
app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user') })
/
sreq.params
object, with the name of the route parameter specified in the path as their respective keys. Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params) })
app.route()
app.route('/book') .get(function (req, res) { res.send('Get a random book') }) .post(function (req, res) { res.send('Add a book') }) .put(function (req, res) { res.send('Update the book') })
express.Router
class to create modular, mountable route handlers.
Router
instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.req
), the response object ( res
), and the next
function in the application’s request-response cycle.
next
function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.const express = require('express'); const app = express(); app.get('/', function(req, res, next) { next(); }); app.listen(3000)
.get()
: HTTP method for which the middleware function applies'/'
: Path (route) for which the middleware function appliesfunction
: The middleware functionreq
: HTTP request argument to the middleware functionres
: HTTP response argument to the middleware functionnext
: Callback argument to the middleware functionapp.listen()
method passing:
const port = 8081; app.listen(port, () => console.log(`Listening on port ${port}...`));
module.exports = function (options) { return function (req, res, next) { // Implement the middleware function based on the options object next() } }
The middleware can now be used as shown below.
var mw = require('./my-middleware.js') app.use(mw({ option1: '1', option2: '2' }))
An Express Application can use the following types of middleware:
app
object by using the app.use()
and app.METHOD()
functions, where METHOD
is the HTTP method of the request that the middleware function handles (such as GET
, PUT
, or POST
) in lowercase.express.Router()
.router.use()
and router.METHOD()
functions.err
, req
, res
, next
)):app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') })
Function | Action | Arguments |
---|---|---|
express.static(root, [options]) |
serves status assets such as HTML files, images, and so on. | root : specifies the root directory options : options object |
express.json([options]) |
parses incoming requests with JSON payloads | options : options object |
express.urlencoded([options]) |
parses incoming requests with URL-encoded payloads | options : options object |
$ npm install cookie-parser
const express = require('express') const app = express() const cookieParser = require('cookie-parser') // load the cookie-parsing middleware app.use(cookieParser())
npm install express-session
express-session
middleware to the app
module. const express = require('express');
const session = require('express-session');
const app = express();
app.set('view engine', 'pug');
app.use(session({
secret: 'a5d63fc5-17a5-459c-b3ba-6d81792158fc',
resave: false,
saveUninitialized: false,
}));
secret
: This is the secret used to sign the session ID cookie. The secret value above was generated using the uuid npm package.
resave
: This option forces the session to be saved into the session store, even if the session was never modified during the request.
saveUninitialized
: This forces an uninitialized session to be saved to the store. An uninitialized session is when a session is new but not modified.
express-session deprecated undefined resave option; provide resave option app.js:8:9
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option app.js:8:9
name
: By default, the express-session middleware uses the name connect.sid
.
Option | Action | Default Value |
---|---|---|
cookie |
Settings object for the session ID cookie. The default value is { path: '/', httpOnly: true, secure: false, maxAge: null }. | |
genid |
Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID. | |
proxy |
Trust the reverse proxy when setting secure cookies (via the “X-Forwarded-Proto” header). | |
rolling |
Force the session identifier cookie to be set on every response. The expiration is reset to the original maxAge , resetting the expiration countdown |
false |
store |
The session store instance, defaults to a new MemoryStore instance |
|
unset |
Control the result of unsetting req.session (through delete, setting to null, etc.). |
keep |
Every session store must be an EventEmitter and implement specific methods. The following methods are the list of required, recommended, and optional.
Method | Required? | |
---|---|---|
store.all(callback) |
Optional | Gets all sessions in the store as an array. The callback should be called as callback(error, sessions) . |
store.destroy(sid, callback) |
Required | Destroys/deletes a session from the store given a session ID ( sid ). The callback should be called as callback(error) once the session is destroyed. |
store.clear(callback) |
Optional | Deletes all sessions from the store. The callback should be called as callback(error) once the store is cleared. |
store.length(callback) |
Optional | Gets the count of all sessions in the store. The callback should be called as callback(error, len) . |
store.get(sid, callback) |
Required | Gets a session from the store given a session ID ( sid ). The callback should be called as callback(error, session) . |
store.set(sid, session, callback) |
Required | Upserts a session into the store given a session ID ( sid ) and session ( session ) object. The callback should be called as callback(error) once the session has been set in the store. |
store.touch(sid, session, callback) |
Recommended | Used to “touch” a given session given a session ID ( sid ) and session ( session ) object. The callback should be called as callback(error) once the session has been touched. |
You can also configure session cookies with the following options that are not set by default: domain
express.json([options])
Request | Application | Response | Router | Middleware |
---|---|---|---|---|
req.accepts() |
app.delete() |
res. append() () |
router.all() |
bodyParser() |
req.acceptsCharsets() |
app.disable() |
res.attachment() |
router.METHOD() |
compress() |
req.acceptsEncodings() |
app.enable() |
res.cookie() |
router.param() |
cookieParser() |
req.acceptsLanguages() |
app.engine() |
res.clearCookie() |
router.route() |
cookieSession() |
req.get() |
app.get() |
res.download() |
router.use() |
csrf() |
req.is() |
app.listen() |
res.end() |
errorHandler() |
|
req.param() |
app.method() |
res.format() |
methodOverride() |
|
req.range() |
app.param() |
res.get() |
morgan() |
|
app.path() |
res.json() |
responseTime() |
||
app.post() |
res.links() |
favicon() |
||
app.put() |
res.location() |
directory() |
||
app.render() |
res.redirect() |
serveStatic() |
||
app.route() |
res.render() |
timeout() |
||
app.set() |
res.send() |
vhost() |
||
app.use() |
res.sendFile() |
session() |
||
res.sendStatus() |
||||
res.set() |
||||
res.status() |
||||
res.type() |
||||
res.vary() |
Request | Response | Application |
---|---|---|
req.app |
res.app |
app.locals |
req.baseUrl |
res.headersSent |
app.mountpath |
req.body |
res.locals |
|
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 |
<form>...</form>
tags, containing at least one input
element of type="submit"
.<form action="/team_name_url/" method="post"> <label for="team_name">Enter name: </label> <input id="team_name" type="text" name="name_field" value="Default name for team."> <input type="submit" value="OK"> </form>
POST
and GET
parameters from the form, and to validate/sanitize their values.npm install express-validator
const { body,validationResult } = require('express-validator');
body([fields, message])
: Specifies a set of fields in the request body (a POST
parameter) to validate and/or sanitize along with an optional error message that can be displayed if it fails the testsvalidationResults(req)
: Runs the validation, making errors available in the form of a validation
result object.GET
) route is used to display a new empty form for creating the object.// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id). router.get('/genre/create', genre_controller.genre_create_get);
POST
) is used for validating data entered by the user, and then saving the information and redirecting to the detail page (if the data is valid) or redisplaying the form with errors (if the data is invalid).// POST request for creating Genre. router.post('/genre/create', genre_controller.genre_create_post);
If you need to use any of the special characters literally (actually searching for a "*", for instance), you must escape it by putting a backslash in front of it.
Errors that occur in synchronous code inside route handlers and middleware require no extra work.
next()
and you do not handle it in a custom error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.res.statusCode
is set from err.status
(or err.statusCode
). If this value is outside the 4xx or 5xx range, it will be set to 500.res.statusMessage
is set according to the status code.err.headers
objectappend
/ prepend
replace
(default), prepend
, or append
blocks.