Here is a short tutorial on Express.js:
- Install Node.js and npm (Node Package Manager) if you don’t have it already.
- Create a new directory for your Express project and navigate to it in the terminal.
- Initialize a new npm project by running
npm init
in the terminal and following the prompts. - Install Express.js by running
npm install express
in the terminal. - Create a new file named
app.js
and open it in your code editor. - Require Express at the top of the file:
javascriptCopy codeconst express = require('express');
const app = express();
- Define a simple route that returns a message:
javascriptCopy codeapp.get('/', (req, res) => {
res.send('Hello, Express!');
});
- Start the Express application by running the following code at the bottom of the
app.js
file:
javascriptCopy codeapp.listen(3000, () => {
console.log('Express app listening on port 3000');
});
- Run the application in the terminal by running
node app.js
. - Visit
http://localhost:3000
in your browser to see the message returned by the route. - Add additional routes to the application as needed, using the
app.get
method to handle GET requests, or theapp.post
method to handle POST requests. - Use the
res.render
method to render HTML templates and pass data to them. You will need to install a template engine such as EJS, Jade, or Handlebars and configure it for use with your Express application.
This tutorial provides a simple introduction to building web applications with Express.js. With its fast, minimalist design and powerful features, Express is a great choice for building web applications and APIs with Node.js.