Creating a Basic Express Server in Nodejs

2024-03-17
By: O. Wolfson

In just a few simple steps, you'll have a functional server running on your local machine, ready to handle requests and serve JSON data.

  1. Install Node.js: Ensure Node.js is installed on your system. You can download it from the official website if you haven't already.

  2. Initialize Your Project: Open your terminal and navigate to the directory where you want to create your project. Then run:

    bash
    npm init -y
    

    This initializes a new Node.js project with default settings.

  3. Install Express: Next, install Express using npm:

    bash
    npm install express
    
  4. Create Your Script: Use the touch command to create a new file named index.js:

    bash
    touch index.js
    
  5. Edit index.js: Open index.js in a text editor and add the following code:

    javascript
    const express = require("express");
    const app = express();
    
    app.get("/data", (req, res) => {
      res.json({
        name: "Billy Watson",
        age: "12",
        gender: "male",
      });
    });
    
    app.listen(3000, () => {
      console.log("Listening on port 3000");
    });
    

    This code sets up a basic Express server with a single route /data that returns a JSON response.

  6. Run Your Server: To run your server and automatically restart it whenever you make changes, you can use nodemon. If you don't have nodemon installed globally, you can use npx to run it:

    bash
    npx nodemon index.js
    

    This command will start your Express server and you should see "Listening on port 3000" logged to the console.

That's it! You now have a basic Express server running on port 3000 with a /data route that returns JSON data.