React - HTTP Server



Http client programming enables the application to connect and fetch data from http server through JavaScript. It reduces the data transfer between client and server as it fetches only the required data instead of the whole design and subsequently improves the network speed. It improves the user experience and becomes an indispensable feature of every modern web application.

Nowadays, lot of server side application exposes its functionality through REST API (functionality over HTTP protocol) and allows any client application to consume the functionality.

React does not provide it's own http programming api but it supports browser's built-in fetch() api as well as third party client library like axios to do client side programming. Let us learn how to do http programming in React application in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter.

Expense Rest API Server

The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. React provides support to create client side application. Express a popular web framework provides support to create server side application.

Let us first create a Expense Rest Api server using express framework and then access it from our ExpenseManager application using browser's built-in fetch api.

Open a command prompt and create a new folder, express-rest-api.

cd /go/to/workspace 
mkdir apiserver 
cd apiserver

Initialize a new node application using the below command −

npm init

The npm init will prompt and ask us to enter basic project details. Let us enter apiserver for project name and server.js for entry point. Leave other configuration with default option.

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (apiserver)
version: (1.0.0)
description: Rest api for Expense Application
entry point: (index.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to \path\to\workspace\expense-rest-api\package.json:
{
   "name": "expense-rest-api",
   "version": "1.0.0",
   "description": "Rest api for Expense Application",
   "main": "server.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
   },
   "author": "",
   "license": "ISC"
}
Is this OK? (yes) yes

Next, install express & cors modules using below command −

npm install express cors
  • express is used to create server side application.

  • cors is a middleware for express framework to configure the client access details.

Next, let us create a file, data.csv and populate it with initial expense data for testing purposes. The structure of the file is that it contains one expense entry per line.

1,Pizza,80,2025-10-10,Food
2,Grape Juice,30,2025-10-12,Food
3,Cinema,210,2025-10-16,Entertainment
4,Java Programming book,242,2025-10-15,Academic
5,Mango Juice,35,2025-10-16,Food
6,Dress,2000,2025-10-25,Cloth
7,Tour,2555,2025-10-29,Entertainment
8,Meals,300,2025-10-30,Food
9,Mobile,3500,2025-11-02,Gadgets
10,Exam Fees,1245,2025-11-04,Academic

Next, create a file server.js and include code to load the initial expense data into the javascript object to act as in memory database.

let expenses = [];

loadExpenses();

function findExpenses(){
	return expenses;
}

function findExpenseById(id){
	console.log(id);
	return expenses.filter( item => item.id == id);
}

function insert(data){
	item = {}
	item.id = rec[0]
	item.name = rec[1];
	item.amount = parseFloat(rec[2]);
	item.spend_date = new Date(rec[3]);
	item.category = rec[4];
    console.log(item);
	expenses.push(item);
}

function update(data){
	item = {}
	item.id = rec[0]
	item.name = rec[1];
	item.amount = parseFloat(rec[2]);
	item.spend_date = new Date(rec[3]);
	item.category = rec[4];
	
	const updatedUsers = expenses.map((expense) =>
        expense.id === rec[0] ? { item } : expense
    );
	console.log(data);
}

function remove(id){
	console.log(id);
	let newExpenses = expenses.filter(item => item.id !== id);
	expenses = newExpenses;
	
}

function loadExpenses() {
   readCsv("data.csv", function (data) {
      console.log(data);

      data.forEach(function (rec, idx) {
         item = {}
		 item.id = rec[0]
         item.name = rec[1];
         item.amount = parseFloat(rec[2]);
         item.spend_date = new Date(rec[3]);
         item.category = rec[4];

         expenses.push(item);
      })
   })
}
function readCsv(file, callback) {
   fs.readFile(file, 'utf-8', function (err, data) {
      if (err) throw err;
      var lines = data.split('\r\n');
      var result = lines.map(function (line) {
         return line.split(',');
      });
      callback(result);
   });
}

Next, update the file, server.js and include the actual code to list, add, update and delete the expense entries.

var express = require("express")
var cors = require('cors')
var app = express()
app.use(cors());
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var HTTP_PORT = 8000
var fs = require('fs');

let expenses = [];

loadExpenses();

function findExpenses(){
	// console.log(expenses);
	return expenses;
}

function findExpenseById(id){
	console.log(id);
	return expenses.filter( item => item.id == id);
}

function insert(data){
	item = {}
	item.id = rec[0]
	item.name = rec[1];
	item.amount = parseFloat(rec[2]);
	item.spend_date = new Date(rec[3]);
	item.category = rec[4];
    console.log(item);
	expenses.push(item);
}

function update(data){
	item = {}
	item.id = rec[0]
	item.name = rec[1];
	item.amount = parseFloat(rec[2]);
	item.spend_date = new Date(rec[3]);
	item.category = rec[4];
	
	const updatedUsers = expenses.map((expense) =>
        expense.id === rec[0] ? { item } : expense
    );
	console.log(data);
}

function remove(id){
	console.log(id);
	let newExpenses = expenses.filter(item => item.id !== id);
	expenses = newExpenses;
	
}

function loadExpenses() {
   readCsv("data.csv", function (data) {
      console.log(data);

      data.forEach(function (rec, idx) {
         item = {}
		 item.id = rec[0]
         item.name = rec[1];
         item.amount = parseFloat(rec[2]);
         item.spend_date = new Date(rec[3]);
         item.category = rec[4];

         expenses.push(item);
      })
   })
}
function readCsv(file, callback) {
   fs.readFile(file, 'utf-8', function (err, data) {
      if (err) throw err;
      var lines = data.split('\r\n');
      var result = lines.map(function (line) {
         return line.split(',');
      });
      callback(result);
   });
}

app.listen(HTTP_PORT, () => {
   console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});
app.get("/", (req, res, next) => {
   res.json({ "message": "Ok" })
});
app.get("/api/expenses", (req, res, next) => {
	res.json(findExpenses());
});
app.get("/api/expense/:id", (req, res, next) => {
   var id = req.params.id;
   res.json(findExpenseById(id));
});
app.post("/api/expense/", (req, res, next) => {
   var errors = []
   if (!req.body.item) {
      errors.push("No item specified");
   }
   var data = {
	  id: req.body.id,
      name: req.body.name,
      amount: req.body.amount,
      category: req.body.category,
      spend_date: req.body.spend_date,
   }
   insert(data);
   res.json(findExpenses());
})
app.put("/api/expense/:id", (req, res, next) => {
   var id = req.params.id;
   var errors = []
   if (!req.body.item) {
      errors.push("No item specified");
   }
   var data = {
      _id: id,
      name: req.body.name,
      amount: req.body.amount,
      category: req.body.category,
      spend_date: req.body.spend_date,
   }
   update(data);
   res.json(findExpenses());
})
app.delete("/api/expense/:id", (req, res, next) => {
   var id = req.params.id;
   remove(id);
   res.json(findExpenses());
})
app.use(function (req, res) {
   res.status(404);
});

Now, it is time to run the application.

npm run start

Next, open a browser and enter http://localhost:8000/ in the address bar.

{ 
   "message": "Ok" 
}

It confirms that our application is working fine.

Finally, change the url to http://localhost:8000/api/expense and press enter. The browser will show the initial expense entries in JSON format.

[
   ...
   {
      "name": "Pizza",
      "amount": 80,
      "spend_date": "2025-10-10T00:00:00.000Z",
      "category": "Food",
      "id": "1"
   },
   ...
]
Advertisements