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}!`));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.