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:
npm init -yThis initializes a new Node.js project with default settings.
-
Install Express: Next, install Express using npm:
npm install express -
Create Your Script: Use the
touchcommand to create a new file namedindex.js:touch index.js -
Edit
index.js: Openindex.jsin 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"); });This code sets up a basic Express server with a single route
/datathat 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 havenodemoninstalled globally, you can usenpxto run it:npx nodemon index.jsThis 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.