Setting up the server
Setting Up a Server for Full Stack Development
In this tutorial, we will set up a server for a full-stack application using Node.js and Express. This foundational step will help us integrate our front-end and back-end, bringing together everything we've learned so far in the course.
Prerequisites
Before we get started, make sure you have Node.js and npm (Node Package Manager) installed. This will allow us to create our server and manage dependencies.
Step 1: Initialize the Project
-
Create a New Folder: Start by creating a new folder for this project. Inside your terminal, navigate to the desired location and create a folder named
fullstack-server
.mkdir fullstack-server cd fullstack-server
-
Initialize npm: Use npm to initialize the project. This will create a
package.json
file that helps manage project dependencies.npm init -y
The
-y
flag automatically answers "yes" to all prompts, setting default values for thepackage.json
file.
Step 2: Set Up the Folder Structure
-
Create Folders: Create a folder named
public
inside your project. This folder will contain all static files, such as CSS or images, that your server needs to access publicly.mkdir public
-
Move Assets: Move any relevant CSS or JavaScript files into the
public
folder.
Step 3: Install Dependencies
Next, we need to install a few essential packages for our server:
- Express: A fast, minimalist framework for Node.js.
- MongoJS: A Node.js library for interacting with MongoDB (optional, as per personal preference).
- Body-Parser: Middleware for handling incoming request bodies.
Use the following command to install these packages:
npm install express mongojs body-parser --save
Step 4: Create the Server File
-
Create a Server File: Create a file named
server.js
inside the newly createdsource
folder. This will be our main server file. -
Add Constants: Let's start by importing the modules we installed and initializing Express.
const express = require('express'); const mongojs = require('mongojs'); const bodyParser = require('body-parser'); const app = express();
Step 5: Set Up Middleware
-
Static Folder: Make the
public
folder available as a static directory for the server. This means any files inside thepublic
folder can be accessed directly by visiting the appropriate URL.app.use(express.static('public'));
-
Body-Parser Setup: Configure the middleware to handle URL-encoded data, ensuring we can access data from POST requests.
app.use(bodyParser.urlencoded({ extended: true }));
Step 6: Define Routes
Now, we'll set up a couple of basic routes.
-
GET Route for Registration: We'll start by setting up a simple
GET
route to return a "Got it" response when visiting/register
.app.get('/register', (req, res) => { res.send('Got it'); });
-
POST Route for Registration: Set up a
POST
route that will handle data submissions for our registration form.app.post('/register', (req, res) => { res.send('Posted'); });
Step 7: Start the Server
Finally, we need to configure our app to start listening on a specific port.
const PORT = 3001;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This will start the server on http://localhost:3001
.
Step 8: Test the Server
To verify that everything is working correctly, run the following command in your terminal:
node source/server.js
If all went well, you should see the message: "Server is running on port 3001". You can then navigate to http://localhost:3001/register
in your browser to see the "Got it" message.
Summary
In this tutorial, we've successfully set up an Express server using Node.js, configured routes for handling incoming requests, and used middleware to serve static files and parse request bodies.
Note (2023 Update): Currently, there are better alternatives to
MongoJS
, such asMongoose
, which provides a more modern and feature-rich way of interacting with MongoDB. If you're starting a new project, consider switching to Mongoose for better support and schema management.
Ready to Level Up Your Skills?
Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!
Enroll Now for Free!