Welcome to Typing Express, your ultimate guide to learning Node.js using the popular Express.js framework! In this lesson, we'll explore the basics of Node.js, dive into Express.js, and create a real-world project together. Let's get started! 🎯
Before we dive into Express.js, let's quickly understand what Node.js is and why we need it.
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows us to run JavaScript on the server-side, making it possible to create fast and scalable network applications.
Why Node.js? 📝
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web applications and APIs. It simplifies the process of routing, handling requests, and managing responses.
To follow along, make sure you have Node.js installed on your machine. You can download it from official Node.js website.
Once Node.js is installed, open your terminal and run:
npm init -y
npm install expressThis command creates a new Node.js project and installs Express.js.
Let's create a simple "Hello World" application. Create a new file called app.js and paste 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 is running at http://localhost:${port}`);
});This code creates an Express.js server, sets up a route to display "Hello World!", and starts the server on port 3000. To run the application, save the file and run:
node app.jsNow, if you navigate to http://localhost:3000 in your browser, you should see "Hello World!" ✅
In Express.js, routes are handlers for specific URL paths. They determine what happens when a user requests a particular URL.
Let's create a new route that displays a personalized message. Edit app.js and add the following code:
app.get('/', (req, res) => {
const name = req.query.name || 'World';
res.send(`Hello ${name}!`);
});
app.get('/about', (req, res) => {
res.send('This is the about page.');
});Now, if you navigate to http://localhost:3000 in your browser, you should see "Hello World!". If you navigate to http://localhost:3000/?name=John, you should see "Hello John!". Also, navigating to http://localhost:3000/about should display "This is the about page."
What is the purpose of Express.js?
We've covered the basics of Node.js and Express.js, and created a simple Express.js application. In the next sections, we'll delve deeper into routing, handling forms, and connecting to a database. Stay tuned! 🚀