Express
BootcampBackend2020-12-17
Express Routes
A route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern.
We use the express.Router middleware as it allows us to group the route handlers for a particular part of a site together and access them using a common route-prefix.
Defining and using separate route modules
// wiki.js - Wiki route module.
var express = require('express');
var router = express.Router();
// Home page route.
router.get('/', function (req, res) {
res.send('Wiki home page');
})
// About page route.
router.get('/about', function (req, res) {
res.send('About this wiki');
})
module.exports = router;then in app.js:
var wiki = require('./wiki.js');
// ...
app.use('/wiki', wiki);The two routes defined in our wiki route module are then accessible from /wiki/ and /wiki/about/.
Note: Router functions are Express middleware, which means that they must either complete (respond to) the request or call the next function in the chain. In the case above we complete the request using send(), so the next argument is not used (and we choose not to specify it).The router function above takes a single callback, but you can specify as many callback arguments as you want, or an array of callback functions. Each function is part of the middleware chain, and will be called in the order it is added to the chain (unless a preceding function completes the request).
Route paths
- ?: /ab?cd’ will match endpoints acd or abcd.
- +: ‘/ab+cd’ will match endpoints abcd, abbcd, abbbcd, and so on.
- : ‘ab\cd’ will match endpoints abcd, abXcd, abSOMErandomTEXTcd, and so on.
- (): ‘/ab(cd)?e’ will peform a ? match on (cd) —it will match abe and abcde.
Route parameters
Route parameters are named URL segments used to capture the values specified at their position in the URL.
The named segments are prefixed with a colon and then the name (e.g. /:yourparametername/. The captured values are stored in the req.params object using the parameter names as keys (e.g. req.params.yourparametername).
//http://localhost:3000/users/34/books/8989
app.get('/users/:userId/books/:bookId', function (req, res) {
// Access userId via: req.params.userId
// Access bookId via: req.params.bookId
res.send(req.params);
})examples APIs:
- catalog/ — The home/index page.
- catalog/<objects>/ — The list of all books, bookinstances, genres, or authors (e.g. /catalog/books/, /catalog/genres/, etc.)
- catalog/<object>/<id> — The detail page for a specific book, bookinstance, genre, or author with the given
_idfield value (e.g. /catalog/book/584493c1f4887f06c0e67d37). - catalog/<object>/create — The form to create a new book, bookinstance, genre, or author (e.g. /catalog/book/create).
- catalog/<object>/<id>/update — The form to update a specific book, bookinstance, genre, or author with the given
_idfield value (e.g. /catalog/book/584493c1f4887f06c0e67d37/update). - catalog/<object>/<id>/delete — The form to delete a specific book, bookinstance, genre, author with the given
_idfield value (e.g. /catalog/book/584493c1f4887f06c0e67d37/delete).
Express Static Files and templates
1.Serving static files
You can use the express.static middleware to serve static files, including your images, CSS and JavaScript
(static() is the only middleware function that is actually part of Express).
For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named ‘public’ at the same level as where you call node:
app.use(express.static('public'));Any files in the public directory are served by adding their filename (relative to the base “public” directory) to the base URL. So for example:
http://localhost:3000/images/dog.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/about.htmlYou can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware
(the order that middleware is called is based on your declaration order).
app.use(express.static('public'));
app.use(express.static('media'));You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix “/media”:
app.use('/media', express.static('public'));Now, you can load the files that are in the public directory from the /media path prefix.
http://localhost:3000/media/images/dog.jpg
http://localhost:3000/media/video/cat.mp4
http://localhost:3000/media/cry.mp32.Rendering Data (Views)
var express = require('express');
var app = express();
// Set directory to contain the templates ('views')
app.set('views', path.join(__dirname, 'views'));
// Set view engine to use, in this case 'some_template_engine_name'
app.set('view engine', 'some_template_engine_name');Express Middleware
-
应用级中间件
app.use((req, res, next) => { next(); }); app.use('/usr/:id', (req, res, next) => { next('route'); }) -
路由级中间件
var router = express.Router(); router.use('/user/:id', (req, res, next) => { next(); }) - 错误处理中间件: 4xx, 500, 5xx
-
内置中间件
app.use(express.static('public')) app.use(express.static('uploads')) app.use(express.static('files')) -
第三方中间件
app.use(cookieParser());
Other Express modules
body-parser: This parses the body portion of an incoming HTTP request and makes it easier to extract different parts of the contained information. For example, you can use this to read POST parameters.cookie-parser: Used to parse the cookie header and populate req.cookies (essentially provides a convenient method for accessing cookie information).debug: A tiny node debugging utility modelled after node core’s debugging technique.morgan: An HTTP request logger middleware for node.serve-favicon: Node middleware for serving a favicon (this is the icon used to represent the site inside the browser tab, bookmarks, etc.).request:socket.io:mongoose:redis:Helmet: a middleware package that can help protect your app from some well-known web vulnerabilities by setting appropriate HTTP headers
