Creating a simple local server from scratch using node and express

greenteabiscuit

Reishi Mitani

Posted on November 15, 2020

Creating a simple local server from scratch using node and express

Objectives

  • Create a local server on your machine using node.js We will first create a simple app that shows hello world and then use express.js for routing. Finally, we will create some APIs and route them.

Prerequisites

  • Mac OS Catalina

Create an app with a simple local server that returns Hello World

// create your own directory
$ mkdir node-practice && cd node-practice
// initialize your project
$ npm init -y
// create your app.js
$ touch app.js
$ vi app.js
Enter fullscreen mode Exit fullscreen mode

Edit your app.js.

const http = require('http');
const server = http.createServer((req, res)=>{
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
})
server.listen(8080);
Enter fullscreen mode Exit fullscreen mode

Run the command below, and access localhost:8080. You should see Hello World appear in the page.

$ node app.js
Enter fullscreen mode Exit fullscreen mode

Alt Text

Introducing express

We will install express.

$ npm install express -save
Enter fullscreen mode Exit fullscreen mode

Create our public folder

$ mkdir public && cd public
$ touch index.html
$ mkdir css img js
Enter fullscreen mode Exit fullscreen mode

Your folders should look like this now, excluding the node_modules.

$ tree -I node_modules
.
├── app.js
├── package-lock.json
├── package.json
└── public
    ├── css
    ├── img
    ├── index.html
    └── js

4 directories, 4 files

Enter fullscreen mode Exit fullscreen mode

We will create the following files inside each of our files.

node-practice/public$ cd css && touch sample.css
node-practice/public$ cd js && touch sample.js
Enter fullscreen mode Exit fullscreen mode

I will have a sample photo inside my img folder.

Alt Text

So now your folders should look like this.

$ tree -I node_modules
.
├── app.js
├── package-lock.json
├── package.json
└── public
    ├── css
    │   └── sample.css
    ├── img
    │   └── sample.jpeg
    ├── index.html
    └── js
        └── sample.js

4 directories, 7 files
Enter fullscreen mode Exit fullscreen mode

For our index.html:

<!DOCTYPE html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>TEST</title>
    <link rel="stylesheet" href="/css/sample.css">
  </head>

  <body>
    <h1>Hello World!</h1>
    <p id="hoge"></p>
    <div>
      <img src="/img/sample.jpeg">
    </div>
    <script src="/js/sample.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

For our sample.js:

/* /public/js/sample.js */
{
  const el = document.getElementById('hoge');
  el.innerText = 'HAHAHAHAHAHAHA!!!!';
}

Enter fullscreen mode Exit fullscreen mode

For our sample.css:

/* /public/css/sample.css */
h1 {
  font-size: 1.5rem;
  color: #0000ff;
}
img {
  max-width: 100%;
}
Enter fullscreen mode Exit fullscreen mode

Edit our app.js

const express = require('express');
const app = express();
const path = require('path');

app.listen(8080, () => {
  console.log('Running at Port 8080...');
});

app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res) => {
  res.sendStatus(404);
});
Enter fullscreen mode Exit fullscreen mode

When you run the following, you should see the web page on localhost:8080.

$ node app.js
Enter fullscreen mode Exit fullscreen mode

Alt Text

Create our APIs

We will create our apis, by creating a folder first.

// at the root directory of the project.
$ mkdir api && cd api
$ touch data.json index.js
Enter fullscreen mode Exit fullscreen mode

We will create some random data in data.json:

{
  "id": "W0001",
  "title": "I Love Cats and Dogs",
  "price": 3000000000000
}
Enter fullscreen mode Exit fullscreen mode

For index.js, we export our api router.

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

router.use(express.json());

router.get('/foo', (req, res) => {
    res.sendFile(__dirname + '/data.json', (err) => {
        if (err) {
            res.sendStatus(400);
        } else {
            console.log('completed');
        }
    });
});

router.route('/bar')
    .get((req, res) => {
        res.json(req.query);
    })
    .post((req, res) => {
        const nameArray = ['id', 'name', 'address'], failed = nameArray.some(v=>!req.body[v]);
        if (failed) {
            res.sendStatus(400);
        } else {
            res.sendStatus(200);
        }
    });

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Our folders should look like this now.

$ tree -I node_modules
.
├── api
│   ├── data.json
│   └── index.js
├── app.js
├── package-lock.json
├── package.json
└── public
    ├── css
    │   └── sample.css
    ├── img
    │   └── sample.jpeg
    ├── index.html
    └── js
        └── sample.js

5 directories, 9 files
Enter fullscreen mode Exit fullscreen mode

Now, we will edit our app.js in our root directory.

const express = require('express');
const app = express();
const path = require('path');
const api = require('./api/');

app.listen(8080, () => {
    console.log('Running at port 8080...');
});

app.use('/api', api);
app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res) => {
    res.sendStatus(404);
});
Enter fullscreen mode Exit fullscreen mode

Now, we run node app.js.

Testing the APIs

Let's use Advanced REST Client to see how the APIs are working.

When we throw http://localhost:8080, we get the following result.

Alt Text

When we throw http://localhost:8080/api/foo, we get the data.json.

Alt Text

When we throw http://localhost:8080/api/bar?name=johndoe&address=USA&age=17, we get the json from the URL values.

Alt Text

Finally, let's POST some data using the bar api. We can add it by editing the body parameters.

Alt Text

Now we can see that the APIs are working, both GET and POST!

Hope this helps.

💖 💪 🙅 🚩
greenteabiscuit
Reishi Mitani

Posted on November 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related