Here is a short practice on Express.js:
- Create a new Express.js project using the steps outlined in the previous tutorial.
- Add a new route to the application that returns a message in JSON format.
javascriptCopy codeapp.get('/json', (req, res) => {
res.json({ message: 'Hello, Express!' });
});
- Add a new route to the application that accepts a name parameter and returns a personalized message.
javascriptCopy codeapp.get('/greet/:name', (req, res) => {
res.send(`Hello, ${req.params.name}!`);
});
- Add a new route to the application that returns a HTML page. You will need to install and configure a template engine such as EJS, Jade, or Handlebars for this step.
javascriptCopy codeapp.get('/template', (req, res) => {
res.render('index', { message: 'Hello, Express!' });
});
- Start the Express application and visit each of the new routes in your browser to see the results.
- Try adding additional routes to the application and experiment with the different features of Express.js, such as middleware functions and query parameters.
This practice will give you hands-on experience 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.