| 2024-03-17

Creating a Basic Express Server in Nodejs

    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:

      npm init -y
      
      bash

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

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

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

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

      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");
      });
      
      javascript

      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:

      npx nodemon index.js
      
      bash

      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.


    Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.