November 7, 2024

UPDATED November 21, 2024

Creating a server in node(Express)

creating servers using express
Creating a server in node(Express)
Creating a server with node js
a) custom server creation
1. Set Up Your Project

First, you'll need to create a new directory for your project and navigate into it:

shell
mkdir my-node-server
cd my-node-server

Then, initialize a new Node.js project:

shell
npm init -y
2. Install Required Packages

You'll need to install the express package, which is a popular framework for building web servers in Node.js and nodemon a popular tool in Node.js development that monitors your project files for any changes and automatically restarts the server when it detects updates. This feature is extremely useful during development, as it speeds up the process by eliminating the need to manually stop and restart the server every time you make a change to your code:

shell
npm install express nodemon
3. Create your server file
javascript
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}`);
});
b) Using Express application generator

express docs

Use the application generator tool, express-generator, to quickly create an application skeleton.

You can run the application generator with the npx command (available in Node.js 8.2.0).

shell
npx express-generator

For earlier Node versions, install the application generator as a global npm package and then launch it:

shell
$ npm install -g express-generator
$ express
Basic routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

javascript
app.METHOD(PATH, HANDLER)

Where:

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.
  • javascript
    app.get('/about', (req, res) => {
    res.send('About Us');
    });
    app.get('/contact', (req, res) => {
    res.send('Contact Us');
    });
    handling post requests

    To handle POST requests, you can use the app.post() method. You'll also need to add middleware to parse the request body:

    javascript
    app.use(express.json());
    app.post('/submit', (req, res) => {
    const data = req.body;
    res.send(`Data received: ${JSON.stringify(data)}`);
    });
    Serving static files in express

    To serve static files such as images, CSS files, and JavaScript files, use the express.static middleware:

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

    set up an index.js

    javascript
    const express = require('express');
    const bodyParser = require('body-parser');
    // Initialize Express app
    const app = express();
    // Middleware to parse JSON requests
    app.use(bodyParser.json());
    // Sample users array (for example purposes)
    const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Mike Brown' }
    ];
    //get users
    app.get('/users', (req, res) => {
    res.send(users);
    });
    // Get a user by ID
    // Create a user route
    app.post('/users', (req, res) => {
    const user = req.body; // Get user details from the request body
    // Check if user exists (basic validation)
    if (!user.name || !user.email) {
    return res.status(400).send('Name and Email are required');
    }
    // Add user to the array
    users.push(user);
    // Send response
    res.status(201).send({ message: 'User created successfully', user });
    });
    // Start the server
    const PORT = 3005;
    app.listen(PORT, () => {
    console.log(Server is running on port ${PORT});
    });

    this implements but store the relevant data in an array, users post data to the /users endpoint and the data is temporarily stored in an array which is used to validate the user

    Implementation using mongo db

    setup a server.js

    javascript
    const express = require('express');
    const bodyParser = require('body-parser');
    const mongoose = require('mongoose'); // Import mongoose
    // Initialize Express app
    const app = express();
    // Middleware to parse JSON requests
    app.use(bodyParser.json());
    // MongoDB connection string
    const mongoURI = process.env.CONNECTION_STRING; // Replace with your actual MongoDB URI
    // Connect to MongoDB
    mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.error('MongoDB connection error:', err));
    // Define a Mongoose Schema for Users
    const userSchema = new mongoose.Schema({
    name: {
    type: String,
    required: true
    },
    email: {
    type: String,
    required: true
    }
    });
    // Create a Mongoose model for Users
    const User = mongoose.model('User', userSchema);
    // Sample users array (for example purposes)
    const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Mike Brown' }
    ];
    // Get all users
    app.get('/users', async (req, res) => {
    try {
    const users = await User.find(); // Fetch users from MongoDB
    res.send(users);
    } catch (err) {
    res.status(500).send('Error fetching users');
    }
    });
    // Create a user route
    app.post('/users', async (req, res) => {
    const { name, email } = req.body;
    // Validate request body
    if (!name || !email) {
    return res.status(400).send('Name and Email are required');
    }
    try {
    // Create a new user and save to MongoDB
    const newUser = new User({ name, email });
    await newUser.save();
    res.status(201).send({ message: 'User created successfully', user: newUser });
    } catch (err) {
    res.status(500).send('Error creating user');
    }
    });
    // Start the server
    const PORT = 3005;
    app.listen(PORT, () => {
    console.log(Server is running on port ${PORT});
    });
    Implementation with mongo db for user management and authentication with jwt

    Espress contact_backend with authentication

    Go to the below and clone the repo:

    setup a .env

    javascript
    CONNECTION_STRING =
    PORT = 3000
    ACCESS_TOKEN_SECRET =

    Run this in the terminal to generate ACCESS_TOKEN_SECRET

    shell
    node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
    or
    openssl rand -base64 64

    then:

    shell
    npm install && npm run dev

    Latest Articles

    More Articles

    Setting up jwt authentication, routes and a postgres connection

    how to connect an express application to postgres and setup jwt authentication

    January 30, 2025

    Intergrating a simulator ecommerce site with mysql, redis

    February 13, 2025
    How can I help you architect your next project?

    Njenga AI

    System Assistant

    👋 Hi! I'm Njenga, Kenneth's AI assistant. How can I help you today?