While frontend development deals with what users see and interact with on a website, backend development manages the server-side operations that users don’t see. The backend is responsible for tasks such as handling requests, managing databases, and responding with the appropriate data to the client (usually a browser). Understanding backend fundamentals is essential for full-stack web development.

In this section, we’ll introduce you to the basics of servers, explain how to set up a backend using Node.js and Express, and walk through handling client requests and responses.



Introduction to Servers

What is a Server?

server is a powerful computer or program that listens for incoming requests from a client (like a browser) and sends back the necessary data. It can serve various types of content, such as:

- Static Content: Files like HTML, CSS, and JavaScript.

Dynamic Content: Data pulled from a database or generated on the fly, such as user profiles or search results.

Servers work based on a client-server model, where clients (web browsers, mobile apps, etc.) send HTTP requests to the server, which processes them and sends back an appropriate HTTP response.


How Do Servers Work?

1. Client Request: The user (client) interacts with a webpage, such as by clicking a button or submitting a form.

2. Server Response: The server receives the client’s request, processes it (e.g., retrieves information from a database), and returns a response to the client, usually in the form of HTML or JSON data.

For example, when you visit a website, your browser sends a request to the server hosting the website. The server processes the request and responds with the content, such as the HTML for the homepage.


Setting Up a Simple Server

To set up a simple server, we will use Node.js, which allows us to run JavaScript on the server-side.



Node.js and Express

What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to use JavaScript for backend programming, meaning you can build the entire stack (frontend and backend) with a single language.

Node.js is known for being fast, scalable, and non-blocking, which makes it ideal for building high-performance, real-time applications such as chat apps or online games.


What is Express?

Express is a minimalist, flexible web application framework built for Node.js. It simplifies the process of setting up a server, routing HTTP requests, handling responses, and managing middleware.

With Express, you can easily handle tasks like:

- Routing: Defining URL paths that respond to client requests (e.g., GET /usersPOST /login).

- Middleware: Functions that run between receiving a request and sending a response, like authentication or logging.

- Template Rendering: Generating dynamic HTML on the server-side.



Installing Node.js and Express

To start building a backend with Node.js and Express, you’ll first need to install them.

1. Install Node.js: Download and install Node.js from the official website: [https://nodejs.org/](https://nodejs.org/).

2. Install Express: After installing Node.js, use the Node package manager (npm) to install Express.

Open your terminal (or command prompt) and run the following commands:


bash

# Initialize a new Node.js project

npm init -y


# Install Express

npm install express



This will create a package.json file (which manages your project dependencies) and install the Express framework.



Setting Up a Basic Server with Express

Here’s how you can set up a basic web server using Express:

1. Create a new JavaScript file called server.js.

2. Write the following code in server.js:


javascript

// Import the Express library

const express = require('express');


// Initialize an Express application

const app = express();


// Define a basic route

app.get('/', (req, res) => {

    res.send('Hello, World!'); // Send a response to the client

});


// Set the app to listen on port 3000

app.listen(3000, () => {

    console.log('Server is running on http://localhost:3000');

});



3. Run the server by executing the following command in your terminal:


bash

node server.js


You should see the message "Server is running on http://localhost:3000" in your terminal. Now, open your web browser and navigate to http://localhost:3000, and you’ll see the message “Hello, World!”.

This is the simplest form of an Express server!




Routing in Express

Routing refers to how an application responds to client requests based on the URL path and the HTTP method (GET, POST, PUT, DELETE). In Express, you can easily set up routes to handle different URLs.

Here’s how to set up routes for different HTTP requests:


javascript

// Route to handle GET request

app.get('/hello', (req, res) => {

    res.send('Hello from the /hello route!');

});


// Route to handle POST request

app.post('/submit', (req, res) => {

    res.send('Form submitted!');

});



In this example:

- GET /hello: Responds with "Hello from the /hello route!" when a user navigates to /hello.

- POST /submit: Responds when a form is submitted to the /submit route.



Handling JSON Data

Express also makes it easy to send and receive JSON data, which is commonly used when building APIs.

To handle JSON data, use the express.json() middleware:


javascript

app.use(express.json());


app.post('/api/data', (req, res) => {

    // Access data sent by the client

    const userData = req.body;

    res.json({ message: 'Data received!', data: userData });

});



In this example, a POST request to /api/data sends a JSON response back to the client, confirming that the data was received.



Middleware in Express

Middleware functions are used to handle tasks that occur between the time the server receives a request and the time it sends a response. They are especially useful for tasks like logging, authentication, and error handling.

Here’s an example of a simple middleware function that logs each request:


javascript

// Middleware to log requests

app.use((req, res, next) => {

    console.log(`${req.method} request for ${req.url}`);

    next(); // Pass control to the next middleware function

});


// Route handler

app.get('/', (req, res) => {

    res.send('Hello, Middleware!');

});


The next() function is essential as it tells Express to move on to the next middleware function in the stack or proceed to the route handler.



Conclusion

With Node.js and Express, you have powerful tools at your disposal for building server-side applications and APIs. You can now create a basic server, define routes, handle JSON data, and implement middleware to build robust and scalable backend systems.

In the next section, we’ll introduce databases and explain how to integrate a database with your Express server to store and retrieve data dynamically.