본문 바로가기
놀기/기초 공부

[Node.js] express.js로 Hello World web server 만들기(왕초보 그냥 따라하기)

by Hi~ 2021. 8. 8.

목차

 

1. node.js & express.js 설치

이미 설치를 했겠지만, 하지 않았다면 아래와 같이 한다.

$ sudo apt update
$ sudo apt install nodejs
$ sudo apt install npm
$ mkdir hello
$ cd hello
$ sudo npm install express --save
npm init으로 package.json 파일 만들고 하실 분은 아래 "5. 참조" 부분 확인

 

 

2. app.js 파일 만들기

설치가 다 되었다면 web server를 만든다.

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

 

끝. web server 작성이 끝났다. 아래와 같이 실행한다.

$ node app.js
Example app listening at http://localhost:3000

 

 

3. 접속 하기

웹 브라우저와 서버가 같은 PC라면 http://localhost:3000으로 접속하면 된다. 만약, 그렇지 않다면 아래와 같이 IP를 확인 후 접속한다.

$ ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.6  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 fe80::9e7a:a289:1214:6f83  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:dc:bb:19  txqueuelen 1000  (Ethernet)
        RX packets 34343  bytes 43180544 (43.1 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 12813  bytes 1612362 (1.6 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

 

 

4. 헤더 출력해보기

작업을 하다 보면 HTTP Header를 확인할 필요가 있다. 아래와 같이 출력해보고 세부적인 것은 인터넷 검색 gogogo.

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
  console.log(req.headers);
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

 

위와 같이 소스를 변경하면 아래와 같이 헤더 정보가 출력된다.

$ node app.js 
Example app listening at http://localhost:3000
{ host: '192.168.0.6:3000',
  connection: 'keep-alive',
  'cache-control': 'max-age=0',
  'upgrade-insecure-requests': '1',
  'user-agent':
   'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36',
  accept:
   'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  'accept-encoding': 'gzip, deflate',
  'accept-language': 'ko-KR,ko;q=0.9',
  'if-none-match': 'W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"' }

 

 

5. 참조

https://expressjs.com/ko/starter/installing.html

 

Express 설치

설치 Node.js가 이미 설치되었다고 가정한 상태에서, 애플리케이션을 보관할 디렉토리를 작성하고 그 디렉토리를 작업 디렉토리로 설정하십시오. $ mkdir myapp $ cd myapp npm init 명령을 이용하여 애플

expressjs.com

 

댓글