Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

r_tanaka
r_tanaka

Posted on • Edited 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 samplecd samplenpm init

find a sample rest api server

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

varhttp=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

npminstallexpress--save
varexpress=require('express'),app=express(),https=require('https')app.get('/',(req,res)=>{letdata=''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)letmsgobjs.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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Tokyo/Japan
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp