DEV Community

Farai Bvuma
Farai Bvuma

Posted on

How to setup a local endpoint with express and Node.js

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.

Initial folder structure

Next, import empress using the following code:

const express = require('express');
const app = express();
Enter fullscreen mode Exit fullscreen mode

You can then proceed to set your port number as follows:

const port = 3000;
Enter fullscreen mode Exit fullscreen mode

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...");
});
Enter fullscreen mode Exit fullscreen mode

Finally, set your app to listen for connections on the previously created port.

app.listen(port, () => {
    console.log(`Listening on port ${port}...`)
})
Enter fullscreen mode Exit fullscreen mode

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:

App listening on port

Open your browser and go to http://localhost:3000/ and the following should be displayed:

App running in browser

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.

Adding JSON file

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");
});
Enter fullscreen mode Exit fullscreen mode

Save the changes, restart your server and navigate to http://localhost:3000/api to display the JSON data. You should see the following:

Endpoint data in webpage

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!

References

  1. Basic Routing

Top comments (0)