Introduction
This guide is for anyone who has ever wanted to setup a local endpoint for use in their projects. This guide assumes that you already have Node.js and express installed.
Setup your local server
To start things off, you'll need to create a js file in the root folder of your project.
Next, import empress using the following code:
const express = require('express');
const app = express();
You can then proceed to set your port number as follows:
const port = 3000;
Now you can setup your basic routing with express. Routing is what determines how your app will respond to client requests from a particular endpoint, in this case your homepage.
app.get("/", (req, res) => {
res.send("Local server running...");
});
Finally, set your app to listen for connections on the previously created port.
app.listen(port, () => {
console.log(`Listening on port ${port}...`)
})
To check if everything is working, open your terminal, navigate to your project folder and run the command node example.js
. You should get the following response in your terminal:
Open your browser and go to http://localhost:3000/
and the following should be displayed:
Congrats, your local server is running!
Creating local endpoint
The first step is to add the JSON file with the data to the root folder of your project. In this example, we have some mock student data.
Go back to your server file(example.js), create a new route to a page of your choice(/api) and send your JSON file to this page.
app.get("/api", (req, res) => {
res.sendFile(__dirname + "/example.json");
});
Save the changes, restart your server and navigate to http://localhost:3000/api
to display the JSON data. You should see the following:
Congrats, you have managed to setup a local endpoint!
Conclusion
With these steps you will be able to quickly setup a local server and connect to a local endpoint. This can be incredibly useful for testing. From here you will be able to send the data that you need to your app's frontend. I hope this was useful and good luck on your programming journey!
Top comments (0)