Learning Express: Part 2: HTTP Request Methods

Learning Express

Express is a popular minimalist web framework for Node.js.


HTTP Request Methods

In the previous section, the function all() was used as an example. It is a catch-all for all possible HTTP verbs. Instead of needing to specify a certain verb, any request using any HTTP verb would be “routed” to the callback function.

GET

In most traditional client-server relationships, GET will be the most common method used. In Express, this is app.get() with the arguments of a path and callback function(s).

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (request, response) => {
    response.send("This is the root route.");
});

app.get('/about', (request, response) => {
    response.send("This is the about route.");
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

POST

Like with GET, POST routes can also be listed using a similar functional structure. It uses app.post() with a path and callback function(s).

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (request, response) => {
    response.send("This is the root route.");
});

app.post('/about', (request, response) => {
    response.send("This is the about route.");
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Working with Response Types

Working with any defined HTTP verb (GET, PUT, POST, DELETE) are available as functions from the Application object, including the much larger set such as TRACE or MOVE.

As part of the Response object, it is also possible to send textual or another type (send()) or work with JSON (json()) directly.

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (request, response) => {
    response.json({"response": "This is the root route."});
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));