Web server, we've all heard of them, but how do they work and how do we create one?
That's the question we're going to answer today.
A Web Server is a piece of software that listens to web requests sent from a client: A browser, script or mobile app. It recieves the request, extract required data, perform some operations and return a response.
That's all web server is, so lets create one.
Our server will be a really simple one with a single endpoint to get our information, a random cat fact and the current timestamp.
Let's get our hand dirty and write some code.\n\nFirst things first, we need to install some stuff to setup our environmen.
After installing these, open up your terminal or command prompt\n\nThe commands i'll be using are linux commands, so please look up their equivalent in you OS
In the terminal create a folder and enter
mkdir server
cd server/
And open it in vscode with
code .
then open the terminal with Ctl + j and run
npm init
touch index.js
Now we have a package.json file and an index.js file,
Install dependencies with
npm i express
npm i --save-dev nodemon
open the package.json file and paste this
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "Your name",
"type": "module",
"license": "ISC",
"dependencies": {
"express": "^5.1.0"
},
"devDependencies": {
"nodemon": "^3.1.10"
}
}
Great, now we have our scripts in place
create a file for fetching cat data with
touch cats.js
open it and paste
const API_URL = "https://catfact.ninja/fact";
export const getCatFact = async () => {
try {
const res = await fetch(API_URL, {
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
return { status: "success", data: data.fact };
} catch (e) {
return { status: "error", data: "Failed to fetch cat fact" };
}
};
getCatFact();
This code will handle fetching a random cat fact and handle errors if any
now in our index.js, paste this
import express from "express";
import cors from "cors";
import { getCatFact } from "./cats.js";
const PORT = 3000;
const app = express();
app.use(
cors({
origin: ["http://localhost:3000"],
})
);
app.use("/me", async (req, res) => {
const currentTimestamp = new Date();
const catFact = await getCatFact();
res.status(catFact.status === "success" ? 200 : 500).json({
status: catFact.status,
user: {
email: "ummuktar917@gmail.com",
name: "Umar Muhammad Muktar",
stack: "Node/Express",
},
timestamp: currentTimestamp,
fact: catFact.data,
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Save all files and in your terminal run
npm run dev
this will run our server on http://localhost:3000
open http://localhost:3000/me in your browser to see the response.
Now let's explain whats going on
the cats.js file sends a request to Catfact to get a random cat fact and return an object with the data and other meta data
the index.js file the imports that function
create the server, and create a route handler at "/me", any requests to /me goes here.
we then create a timestamp with new Date()
grab a random cat fact using our function
then build a response object with our info and status based on the cat fetch status.
And there we have it, we learn how to create a server with nodejs and express, consume external API and build dynamic response objects.
I hope we know all know what a web server is and how to build a simple one.
Follow for more
Top comments (0)