Hey there! If you're new to Node.js, you've probably heard of Express.js—a lightweight, fast, and flexible framework for building web servers and APIs. In this guide, I'll walk you through the basics of Express, showing you how easy it is to get started.
Ready? Let's dive in!
First things first, let's install Express. Make sure you have Node.js and npm (Node's package manager) set up on your machine. Once you're good to go, open your terminal and run this command:
npm install express
Boom! You've just installed Express in your project. It's that simple.
Now, let's build something! Here's how you can create a super simple Express server that listens for requests and responds with "Hello World" when someone visits your site.
const express = require('express'); // Import Express const app = express(); // Initialize your Express app app.get('/', (req, res) => { // Set up a route for GET requests to the root URL res.send('Hello World'); // Send a response }); app.listen(3000, () => { // Tell the app to listen on port 3000 console.log('Server is running on port 3000'); });
If you run this with node app.js and open http://localhost:3000 in your browser, you'll see "Hello World." It's that easy to get a server up and running!
You might have heard the term "middleware" thrown around a lot. Simply put, middleware is just a function that gets executed between a request being received and a response being sent.
Let’s look at a simple example:
app.use((req, res, next) => { console.log('Request received'); next(); // Moves to the next middleware or route });
In this case, every time a request is made, it logs "Request received" to the console. The next() function is crucial here because it allows the request to continue to the next middleware function or route handler. Without it, the request would stop, and no response would be sent.
If you're interested in learning more about how middleware works in detail, check out Understanding Middleware in Express.js with Node.js. It covers different types of middleware, such as router-level, and error-handling middleware.
Routing is how you set up different URLs in your app. You already saw a basic route for the root (/) path, but you can also handle other HTTP methods, like POST, to deal with form submissions or data updates.
app.post('/submit', (req, res) => { res.send('Form submitted!'); });
Now, when a user submits a form to /submit, this route will handle it. You can create as many routes as you need—Express makes it easy!
What if you want to serve images, CSS files, or other static assets? Express has you covered! Just drop those files into a folder, like public, and tell Express where to find them:
app.use(express.static('public'));
Now, any file inside the public folder (like style.css or an image) can be accessed directly by the browser.
In modern apps, you'll often need to handle JSON data—maybe from a form or an API request. Express makes this super easy:
app.use(express.json()); // Add this middleware to parse JSON app.post('/data', (req, res) => { console.log(req.body); // Access the parsed JSON data res.send('Data received!'); });
Now, when a POST request with JSON data is sent to /data, Express will automatically parse the JSON, and you can access it in req.body. Simple, right?
And there you have it—a quick and easy introduction to Express.js! With just a few lines of code, you’ve learned how to:
Express is a powerful framework that makes building web servers and APIs fun and straightforward. As you get more comfortable, you can start exploring more advanced features like routers, error handling, or even integrating with a database.
I hope this guide helps you get started with Express! Keep experimenting, and before you know it, you’ll be building awesome web apps like a pro.
Happy coding!
The above is the detailed content of Express.js Basics: A Beginners Guide - Node.js Tutorial Series - part 10. For more information, please follow other related articles on the PHP Chinese website!