Welcome to our Express App tutorial, designed for both beginners and intermediates! By the end of this lesson, you'll learn how to build a functional web application using Node.js and the Express.js framework. Let's dive right in!
Node.js is an open-source, cross-platform runtime environment for executing JavaScript on the server side. It allows developers to write JavaScript code to create server-side applications, instead of just the client-side scripts that run in a web browser.
Express.js is a popular, minimalist web application framework for Node.js. It simplifies the process of creating web applications and APIs by providing a set of pre-built features and a robust set of APIs.
Before we start, make sure you have Node.js installed on your machine. You can download it from the official Node.js website. After installation, you can verify the installation by running node -v and npm -v in your terminal.
To install Express.js, you'll use Node.js Package Manager (npm). Run the following command in your terminal:
npm install expressNow, let's create our first Express app! Open your terminal and run:
mkdir my-express-app
cd my-express-app
npm init -y
touch app.jsReplace the content of app.js with the following code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});This code creates an Express app, sets up a server that listens on port 3000, and sends the "Hello World!" message when you visit the homepage (http://localhost:3000).
š” Pro Tip: When you're starting a new project, it's best practice to initialize a new Node.js project using npm init to create a package.json file that keeps track of your project's dependencies.
To run your Express app, use the following command in your terminal:
node app.jsNow, if you navigate to http://localhost:3000 in your web browser, you should see "Hello World!" displayed.
Express apps are made up of routes. A route is a URL path that leads to a specific function, allowing you to define what happens when a user navigates to a particular URL.
Let's add a new route for a page titled "About Us":
app.get('/about', (req, res) => {
res.send('About Us');
});To access the "About Us" page, navigate to http://localhost:3000/about in your web browser.
Express allows you to handle parameters in your URLs. For example, let's create a route that accepts a parameter for a user's name:
app.get('/user/:name', (req, res) => {
const name = req.params.name;
res.send(`Hello ${name}!`);
});Now, when you navigate to http://localhost:3000/user/John, you'll see "Hello John!" displayed.
Congratulations! You've created your first Express app. As you continue to learn and practice, you'll discover the vast potential of Node.js and Express.js for building scalable web applications.
Which command is used to install Express.js?
What does Express.js do in a Node.js application?