DEV Community

r_tanaka
r_tanaka

Posted on • Updated on

Let's make a small web app by nodejs.

Write a small node web app with display a result of a rest api.

1. No framework

preparation for local server

mkdir sample
cd sample
npm init

find a sample rest api server

my recommendation is
https://catfact.ninja/fact

var http = require('http'),
    https = require('https')

http.createServer((req, res) => {
    console.log(req.url)
    https.get('https://catfact.ninja/fact', (r) => {
        console.log(r.statusCode)
        r.on('data', (d) => {
            obj = JSON.parse(d)
            res.writeHead(200, {'Content-Type': 'text/html'})
            res.write(`<h1>${obj.fact}</h1>`)
            res.write(`<h2>${obj.length}</h2>`)
            res.end()
        })
    }).on('error', (e) => {
        console.error(e)
    })

}).listen(8080)

2. Let's use Express

Why Express?

Above code has 2 issues.

  1. Unexpected 2 request to the catfact occurs because of favicon.
  2. No process deal with http chunk.

Using the Express is easy way to fix 1st one.

installation web framework

npm install express --save
var express = require('express'),
    app = express(),
    https = require('https')

app.get('/', (req, res) => {
    let data = ''
    https.get('https://catfact.ninja/facts?limit=1000', (r) => {
        console.log(r.statusCode)
        r.on('data', (chunk) => {
            data += chunk
        })
        r.on('end', () => {
            objs = JSON.parse(data)
            let msg
            objs.data.forEach((obj) => msg += `<h1>${obj.fact}</h1>`)
            res.send(msg)
        })
    }).on('error', (e) => {
        console.error(e)
    })
})
app.listen(8080)

Appendix

If you want to pack your app in a docker container.
Read below.

https://nodejs.org/en/docs/guides/nodejs-docker-webapp/

Top comments (0)