Home > Web Front-end > JS Tutorial > body text

Express.js Basics: A Beginner&#s Guide - Node.js Tutorial Series - part 10

Barbara Streisand
Release: 2024-09-27 06:33:02
Original
617 people have browsed it

Express.js Basics: A Beginner

Introduction:

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!


1. Installing Express

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
Copy after login

Boom! You've just installed Express in your project. It's that simple.


2. Creating Your First Express Server

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');
});
Copy after login

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!


3. What’s Middleware?

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
});
Copy after login

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.


4. Routing: The Backbone of Your App

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!');
});
Copy after login

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!


5. Serving Static Files

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'));
Copy after login

Now, any file inside the public folder (like style.css or an image) can be accessed directly by the browser.


6. Handling JSON Data

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!');
});
Copy after login

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?


Wrapping It All Up

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:

  • Install Express,
  • Set up a basic server,
  • Use middleware,
  • Handle different routes,
  • Serve static files,
  • And work with JSON data.

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.


Pro Tips for Your Express Journey

  • Use nodemon: It automatically restarts your server when you make changes. Just run npm install -g nodemon and use nodemon app.js instead of node app.js.
  • Structure your app: As your project grows, you'll want to organize your routes and controllers into separate files. This keeps your code clean and manageable.

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 Beginner&#s Guide - Node.js Tutorial Series - part 10. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!