March 17, 2024
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.
Install Node.js: Ensure Node.js is installed on your system. You can download it from the official website if you haven't already.
Initialize Your Project: Open your terminal and navigate to the directory where you want to create your project. Then run:
bashnpm init -y
This initializes a new Node.js project with default settings.
Install Express: Next, install Express using npm:
bashnpm install express
Create Your Script: Use the touch command to create a new file named index.js:
bashtouch index.js
Edit index.js: Open index.js in a text editor and add the following code:
javascriptconst 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.
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:
bashnpx 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.