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
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);
Run the command below, and access localhost:8080
. You should see Hello World appear in the page.
$ node app.js
Introducing express
We will install express.
$ npm install express -save
Create our public folder
$ mkdir public && cd public
$ touch index.html
$ mkdir css img js
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
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
I will have a sample photo inside my img folder.
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
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>
For our sample.js:
/* /public/js/sample.js */
{
const el = document.getElementById('hoge');
el.innerText = 'HAHAHAHAHAHAHA!!!!';
}
For our sample.css:
/* /public/css/sample.css */
h1 {
font-size: 1.5rem;
color: #0000ff;
}
img {
max-width: 100%;
}
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);
});
When you run the following, you should see the web page on localhost:8080
.
$ node app.js
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
We will create some random data in data.json:
{
"id": "W0001",
"title": "I Love Cats and Dogs",
"price": 3000000000000
}
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;
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
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);
});
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.
When we throw http://localhost:8080/api/foo
, we get the data.json
.
When we throw http://localhost:8080/api/bar?name=johndoe&address=USA&age=17
, we get the json from the URL values.
Finally, let's POST some data using the bar
api. We can add it by editing the body parameters.
Now we can see that the APIs are working, both GET and POST!
Hope this helps.
Top comments (0)