2024-09-09 web, development, javascript
Creating a Basic Express Server in Nodejs
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.
-
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:
This initializes a new Node.js project with default settings.
-
Install Express: Next, install Express using npm:
-
Create Your Script: Use the
touch
command to create a new file namedindex.js
: -
Edit
index.js
: Openindex.js
in a text editor and add the following code: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 havenodemon
installed globally, you can usenpx
to run it: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.