Express in One Lesson
Express is a small framework for building web servers with Node. It maps web addresses to functions that send back responses.
Create the app
The express function returns a new app.
import express from 'express';
const app = express();A JSON route
Requests to /api/hello get a JSON object back.
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from Express' });
});Start the server
The server listens on port 3001 and prints a startup line.
app.listen(3001, () => {
console.log('Server running on port 3001');
});Example
import express from 'express';
const app = express();
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from Express' });
});
const server = app.listen(0, async () => {
const port = server.address().port;
const response = await fetch(`http://localhost:${port}/api/hello`);
const data = await response.json();
console.log(data);
server.close();
});Key points
- An Express app is created by calling the express function.
- app.get registers a function that answers requests to one address.
- The handler receives a request object and a response object.
- res.json sends a JavaScript object back as a JSON response.
- app.listen starts the server on a port so it can take requests.
In this example, an Express app is created and given one route. The route answers /api/hello with a JSON object. The server starts on an open port. The script fetches its own route, prints the JSON it gets back, and then closes the server.
Note
This lesson uses Express alone, with no database.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method sends a JavaScript object back as a JSON response?