Creating a simple server looks like an exciting thing to do. If you're fetching data from other sites, why not create your own server for accessing API data?
It's Easy!!
Let's learn how to make a local server using express.js for your project by following these steps:
First, you need to install Node.js. I assume that you have already installed Node.js on your computer.
Install and setup the server:
First, create the backend server:
mkdir my-app-server
Go to the folder path:
cd my-app-server
npm init:
npm init -y
npm install express:
npm install express
Install cors:
npm install cors
Cors gives access to the server for your project (API call). Otherwise API call in your project will show 'failed to load'.
Then create a file 'index.js'. Now write code in 'index.js'.
const express = require('express');
const app = express();
const cors = require('cors');
const port = process.env.PORT || 5000;
const categories = require('./data/categories.json');
app.use(cors());
app.get('/', (req, res) => {
res.send("Server is running");
});
app.get('/categories', (req, res) => {
res.send(categories);
})
app.listen(port, () => {
console.log(`Server (categories) is running on port: ${port}`);
})
Our data file is categories.json
.
Data of categories.json
file:
[
{
"id": 1,
"category": "World",
"total_news": 150
},
{
"id": 2,
"category": "Politics",
"total_news": 120
},
{
"id": 3,
"category": "Business",
"total_news": 100
},
{
"id": 4,
"category": "Technology",
"total_news": 80
},
{
"id": 5,
"category": "Sports",
"total_news": 90
}
]
Run the server:
Run the server using nodemon:
nodemon index.js
Nodemon helps to update the server in real-time.
Open your web browser and go to http://localhost:5000
. You should see "Server is running" displayed on the page.
If you go to http://localhost:5000/categories
. Then you can see some categories of data.
Now you can easily access this data for your project.
That's why I'm here:
YouTube Tutorial: https://youtu.be/u6q5yqlc8bM?si=RQeVvzZRNYdUA0Wc
Top comments (4)
I think this is a very good introduction. Thanks!
You're welcome. I'm glad you liked it 🩵
This is a great tutorial! Just wondering, do you have any tips for debugging common issues with Express.js servers?
Thank you so much, @fred_functional. I mostly use common tools such as console.log(), npm debug, and error handling. I'm continuing to learn in depth about server error handling and debugging. There are a lot of things I need to learn.