Getting Started with Express
Summary
Express.js is a popular web framework for Node.js that simplifies building web applications and APIs. This tutorial will walk you through creating your first Express application from scratch.
You'll learn the basic steps to set up a new project, install dependencies, write server code, and run your application locally.
Key Vocabulary
Prerequisites
- Node.js installed on your system
- npm installed
- Basic command line knowledge
- A text editor
Step-by-Step Instructions
Create Project Directory
Create a new directory for your Express app.
mkdir my-express-app
Navigate to Project Directory
Change to the newly created directory.
cd my-express-app
Initialize npm Project
Set up a new npm project.
npm init -y
Install Express
Install the Express framework.
npm install express
Create Application Code
Write the main server code.
// Import the Express framework
const express = require('express');
// Create an instance of an Express application
const app = express();
// Define the port number where the server will listen for requests
const PORT = 3000;
// Define a route for the root URL ('/') that sends a welcome message
app.get('/', (req, res) => {
// Send a response to the client with a welcome message
res.send('Welcome to your first Express app!');
});
// Start the server and listen for incoming requests on the specified port
app.listen(PORT, () => {
// Log a message to the console indicating the server is running
console.log(`Server running at http://localhost:${PORT}`);
});
Start the Server
Run the application.
node app.js
Common Issues & Solutions
Solution: Ensure Node.js and npm are installed and in your PATH.
Solution: Change the PORT variable to a different number or stop the conflicting process.
Solution: Check that the server started successfully and visit http://localhost:3000.
Conclusion
You've successfully created and run your first Express.js application!
The server is now running and you can visit http://localhost:3000 to see your app in action.
This is just the beginning - you can now add more routes, middleware, and features to build more complex applications.