Create a Node.js REST API project


This post demonstrates how to create a Node.JS REST API Project.

Project Scaffolding

mkdir eaxapp
cd eaxapp

Create a basic Node.js application:

npm init -y

This will create a basic scaffolding:

Wrote to /Users/syed263/Downloads/eaxapp/package.json:

  "name": "eaxapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [],
  "author": "",
  "license": "ISC"

Install Express Server

npm install express

Nodemon is an optional package (installed globally) which automatically restarts the server after saving server-side code changes. Go ahead and install Nodemon using npm install -g nodemon

sudo npm install nodemon

Create a new index.js file:

const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();

app.use(express.static(__dirname + '/public'));

router.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
    //__dirname : It will resolve to your project folder.

router.get('/about', function (req, res) {
    res.sendFile(path.join(__dirname + '/about.html'));

router.get('/sitemap', function (req, res) {
    res.sendFile(path.join(__dirname + '/sitemap.html'));

//add the router
app.use('/', router);
app.listen(process.env.port || 3000);

console.log('Running at Port 3000');

Create new index.html, about.html, sitemap.html pages.

If you run the page now with nodemon start, you will be faced with a MIME type error.

Refused to execute script from ... because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

This is because the line app.use(express.static(__dirname + ‘/public’)); states that a public directory is required in order to serve up static content. To get around this error, create a new directory called public, and add the necessary script and styles in this directory.

Once the public directory has been added, start the server using:

nodemon start

Leave a comment