Fast, unopinionated, minimalist web framework for Node.js
Express provides a robust web application feature set and many other popular frameworks are built on top of the Express framework.
npm install express
Express package is saved as a dependency in the project's package.json
file.
Node with Express:
import express from 'express';
const hostname = '127.0.0.1';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Welcome to my REST API!');
});
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
- Static file server
- Routing: define how an application’s endpoints (URIs) respond to client requests
- Middlewares: functions that have access to the request object (req), the response object (res) in the application’s request-response cycle.
- Support for several template engines
- Pug (formerly Jade) is the default template engine
- Express application generator
- quick Express app scaffolding, e.g:
npx express-generator --view=pug pug-app
- the app structure created by the generator is just one of many ways to structure Express apps and might need a lot of refactoring to suit your needs
- quick Express app scaffolding, e.g:
- Create a folder
src/public
and add any static files into it, e.g. html, css, js, images, etc. - Serve the files:
app.use('/static', express.static(path.join(__dirname, 'public')));
- Access the files in
public
folder athttp://localhost:3000/static/...
Note: If using ES modules (import
statements instead of CommonJS require()
) and path.join()
when serving static files, you don't have __dirname
variable by default. You need set it manually:
import path from 'path';
import {fileURLToPath} from 'url';
...
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// GET http://localhost:3000/api/resource
app.get('/api/resource', (req, res) => {
const myData = {title: 'This is an item', description: 'Just some dummy data here'};
res.json(myData);
});
Using route parameters (path variables, the preferred way in REST APIs):
// GET http://localhost:3000/api/resource/99
// property name (id) is set in the route definition
app.get('/api/resource/:id', (req, res) => {
console.log('path variables', req.params);
if (req.params.id === '99') {
const myData = {
title: 'This is a specific item, id: ' + req.params.id,
description: 'Just some dummy data here',
};
res.json(myData);
} else {
res.sendStatus(404);
}
});
Using query parameters:
// GET http://localhost:3000/api/resource?id=99&name=foo
app.get('/api/resource', (req, res) => {
if (req.query.id === '99') {
console.log('query params object', req.query);
const myData = {
title: 'This is a specific item, id: ' + req.query.id,
description: 'Just some dummy data here',
};
res.json(myData);
} else {
res.sendStatus(404);
}
});
// needed for reading request body in JSON format
app.use(express.json());
...
// POST http://localhost:3000/api/resource
// sends request data back to client
app.post('/api/resource', (req, res) => {
const body = req.body;
res.status(201);
res.json({your_request: body});
});
Environment variables are used to store configuration settings outside your codebase. They are useful for storing sensitive information like API keys, database credentials, etc.
dotenv is a zero-dependency module that loads environment variables from a .env
file into process.env
.
In the labs we are going to build a REST API with Express. The API will serve data in JSON format and static files. Example API documentation here (Metropolia network / VPN only).
- Create a new project folder for this week's assignments and initialize a new Git repository.
- Add a
.gitignore
file to the project folder. Excludenode_modules
and.env
files from the repository. You can use gitignore.io to generate.gitignore
files. - Create a new branch 'Assignment1' and switch to it:
git checkout -b 'Assignment1'
- Make sure to commit your changes and push to the Git repository regularly.
- Init eslint, editorconfig and prettier to the project. Note that now we are running code in Node, not browser.
- Enable ES Modules in Node.js by adding
"type": "module"
topackage.json
. - Create a new Express project in the project folder based on the 'Hello world' example above.
- install Express:
npm install express
- create an
app.js
file - add the 'Hello world' example code to
app.js
- install nodemon:
npm install -D nodemon
- add a dev script to
package.json
to run the server with nodemon:"dev": "nodemon app.js"
- install Express:
- Serve response in JSON format that returns a cat object:
app.get('/api/v1/cat'... etc.
Object should have the following properties:cat_id
: numbername
: stringbirthdate
: stringweight
: numberowner
: stringimage
: string, URL to an image (e.g.https://loremflickr.com/320/240/cat
)
- To test the application
- run the server with
npm run dev
- open a browser and navigate to
http://localhost:3000/api/v1/cat
- run the server with
- Create new folder 'public' and add a some image file there. Serve the static files from the 'public' folder:
app.use('/public', express.static('public'));
- Test that the image is served correctly by navigating to
http://localhost:3000/public/your-image.jpg
- Add a start script to
package.json
to run the server withnode
instead ofnodemon
:"start": "node app.js"
- Commit and push branch 'Assignment1' to the remote repository.
- Merge the 'Assignment1' branch to the 'main' branch.
- Push your 'main' to a remote repository.
- Serve the project on a server (e.g. Azure, Metropolia ecloud, etc.) and test that it works.