DEV Community

r_tanaka
r_tanaka

Posted on • Edited on

11 6

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/

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs