Home » Setting Up a Node.js Server with Express

Setting Up a Node.js Server with Express

Setting Up a Node.js Server with Express: A Comprehensive Guide

Creating a robust web server is a cornerstone of any modern web application. Node.js and Express have emerged as a dynamic duo in this realm. Here, we delve deep into the process of setting up a server using these tools.

1. Introduction to Node.js and Express

  • Node.js: A JavaScript runtime built on Chrome’s V8 JavaScript engine. It enables JavaScript to be used outside the browser.
  • Express: A fast, unopinionated, minimalist web framework for Node.js.

2. Prerequisites

Before you begin, ensure you have:

  • Node.js and npm (node package manager) installed.
  • A code editor (e.g., Visual Studio Code).
  • Basic understanding of JavaScript.

3. Initial Setup

3.1. Creating a new Node.js project

mkdir myExpressServer
cd myExpressServer
npm init -y

3.2. Installing Express

npm install express

4. Crafting a Basic Server

4.1. Hello World Server

Create a file named server.js and input the following:

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 on http://localhost:${PORT}`);
});

Run the server:

node server.js

Visit http://localhost:3000 to see your server in action.

5. Routes and Middleware

5.1. Defining Routes

Express allows you to define routes effortlessly:

app.get('/about', (req, res) => {
    res.send('About Us Page');
});

5.2. Middleware

Middleware functions are functions that have access to the request and response objects, and the next middleware function in the application’s request-response cycle.

For example, to log details about every request:

app.use((req, res, next) => {
    console.log(`${req.method} request for ${req.url}`);
    next();
});

6. Templating Engines

Express supports several templating engines, with popular ones being Pug, EJS, and Handlebars. Here’s how to use EJS:

npm install ejs

In server.js:

app.set('view engine', 'ejs');

Now, you can render views:

app.get('/home', (req, res) => {
    res.render('home', { title: 'Home' });
});

7. Handling Static Files

Use the express.static middleware:

app.use(express.static('public'));

This serves files from the public directory.

8. Integrating Databases

For demonstration, we’ll use MongoDB with the Mongoose ODM:

npm install mongoose

Connecting to MongoDB:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDatabase', { useNewUrlParser: true, useUnifiedTopology: true });

9. Error Handling

Express has built-in error handling. You can create custom error-handling middleware:

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

10. Conclusion and Next Steps

You’ve now set up a basic Node.js server using Express. The next steps involve diving deeper into middleware, exploring more complex routing, securing your application, and deploying it to production.

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Creating a Simple Express.js Server on Node.js

How to use Authentication in Node.js & React?

Chat Icon