The `app.get()` Function in Express
Express' app.get()
function lets you define a route handler for GET
requests to a given URL. For example, the below code registers a route handler that Express will call when it receives
an HTTP GET request to /test
.
const app = require('express')();
// If you receive a GET request with `url = '/test'`, always
// send back an HTTP response with body 'ok'.
app.get('/test', function routeHandler(req, res) {
res.send('ok');
});
Regular Expressions
The first parameter to app.get()
is called the path
. The path
string supports several special characters that let you use a subset of regular expressions in path strings.
For example, you may see app.get('*')
in tutorials: this registers a route handler for all GET requests.
const app = require('express')();
// Send back an HTTP response with body 'ok' whenever you
// receive a GET request, regardless of the URL.
app.get('*', function routeHandler(req, res) {
res.send('ok');
});
?
, +
, *
, (
, )
, and :
are special characters in Express paths. Although you typically shouldn't use these
characters as literals in URLs, you can escape them with a \
:
const app = require('express')();
// Escape '+' so it is treated as a literal.
app.get('/\\+', function routeHandler(req, res) {
res.send('ok');
});
We typically don't recommend using *
, +
, ?
, (
, or )
in Express route paths. They are rarely useful, especially
since Express supports specifying a JavaScript regular expression as a path:
const app = require('express')();
// Handle any GET request whose URL starts with '/test/'
app.get(/^\/test\//i, function routeHandler(req, res) {
res.send('ok');
});
Route Parameters
Route parameters are essentially variables defined from named sections of the URL.
Express parses the URL, pulls the value in the named section, and stores it in the req.params
property.
const app = require('express')();
// `:userId` is a route parameter. Express will capture whatever
// string comes after `/user/` in the URL and store it in
// `req.params.userId`
app.get('/user/:userId', (req, res) => {
req.params; // { userId: '42' }
res.json(req.params);
});
const server = await app.listen(3000);
// Demo of making a request to the server
const axios = require('axios');
const res = await axios.get('http://localhost:3000/user/42');
res.data; // { userId: '42' }
Route parameters allow you to specify a parameterized GET route handler for a class of URLs. They're very useful for building REST APIs.
Espresso supports:
- Route handlers, like `app.get()` and `app.post()`
- Express-compatible middleware, like `app.use(require('cors')())`
- Express 4.0 style subrouters
Get the tutorial and master Express today!