λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
Second Brain/Node

[Node] express μ›Ή ν”„λ ˆμž„μ›Œν¬ - μ›Ή μ„œλ²„ λ„μš°κΈ°

by 솑두뢀 2022. 5. 29.
728x90
λ°˜μ‘ν˜•

πŸš€express μ›Ή ν”„λ ˆμž„μ›Œν¬ 

  • nodeJSμ—μ„œ κ°€μž₯ 많이 μ‚¬μš©ν•˜λŠ” μ›Ή ν”„λ ˆμž„μ›Œν¬ express
  • μ‚¬μš©μžκ°€ λ³΄λ‚΄λŠ” request μš”μ²­μ„ λ°›μ•„μ„œ μ„œλ²„λŠ” μ‘λ‹΅ν•œλ‹€.
  • λ‚΄κ°€ λ³΄μ—¬μ£Όκ³ μž ν•˜λŠ” 화면을 response 응닡 μ†ŒμŠ€λ‘œ 보여쀀닀.

1. expressλ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  λ‚΄μž₯λͺ¨λ“ˆμ„ ν™œμš©ν•΄μ„œ μ›Ή μ„œλ²„ λ„μš°κΈ°

πŸ”Έ μ½”λ“œ νŒŒμ•…ν•˜κΈ°

1
2
3
4
5
6
const http = require('http');
http.createServer( (request, response) => { 
    response.writeHead(200, {'Content-Type' : 'text/plain'}); 
    response.write('Hello Server');
    response.end();
}).listen(3000);
cs
const http = require('http');
  • NodeJS λ‚΄μž₯ λͺ¨λ“ˆ(http)을 λΆˆλŸ¬μ˜¨λ‹€.
  • node_modules둜 λ”°λ‘œ λ°›μ•„μ˜€μ§€ μ•Šμ•˜λ‹€. (npm install)
http.createServer().listen(3000);
  • http.createServer() : μ„œλ²„λ₯Ό λ„μš°λŠ” 것은 createServer() μ•ˆμ—μ„œ ν•¨μˆ˜λ‘œ μž‘μ„±λœλ‹€.
  • listen(3000) : 포트 3000번으둜 λ„μ›Œλ‹¬λΌ
response.writeHead(200, {'Content-Type' : 'text/plain'});
  • resopnseλ₯Ό 톡해 λ‚΄κ°€ μž‘μ„±ν•œ response 응닡 객체만 보여쀄 수 μžˆλ‹€.
  • writeHead : λ¬Έμ„œ ν˜•μ‹ μž‘μ„±
  • http μƒνƒœμ½”λ“œ : 200 - 응닡성곡
 response.write('Hello Server');
  • 화면에 그렀질 λΆ€λΆ„   

싀행쀑

 

http://localhost:3000/

 


2. express μ‚¬μš©ν•΄μ„œ μ›Ή μ„œλ²„ λ„μš°κΈ°

 

1️⃣package.json 파일 생성 

: μ˜μ‘΄μ„± 및 ν”„λ‘œμ νŠΈμ— λŒ€ν•œ μ„€λͺ…

 

 

2️⃣express μ„€μΉ˜

: λ‹€λ₯Έ μ‚¬λžŒλ“€μ΄ κ³΅μœ ν•œ express νŒ¨ν‚€μ§€λ₯Ό λ‹€μš΄λ‘œλ“œ λ°›λŠ”λ‹€.

package.json
package.json - express μ„€μΉ˜ 확인 κ°€λŠ₯

 

πŸ”Έ μ½”λ“œ νŒŒμ•…ν•˜κΈ°

μ‚¬μš©μžμ˜ req λ°›μ•„μ„œ λ‚΄κ°€ μ§€μ •ν•œ 응닡(res)만 μ‚¬μš©μžκ°€ λ³Ό 수 μžˆλ‹€.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// express setting
const express = require('express');
const app = express();
 
// port μ§€μ •
const port = 3000;
 
// get μš”μ²­ : ν™”면을 λ„μš°κΈ°
app.get('/', ( req, res ) => {
    res.send('hello express');
});
//  url μΆ”κ°€
app.get('/brave', ( req, res ) => {
    res.send('Be Brave');
});
 
// μ›Ή μ„œλ²„ λ„μš°λŠ” createServer μ—­ν• 
app.listen( port, ()  => {
    console.log('Express listening on port', port);
});
cs

Q. url을 μΆ”κ°€ν•˜λŠ” μˆ˜μ •μ‚¬ν•­ ν›„ 3000번 ν¬νŠΈκ°€ λŒμ•„κ°€κ³  μžˆμŒμ—λ„ λ™μž‘ν•˜μ§€ μ•ŠλŠ”λ‹€λ©΄ ❔

>. ctrl + cλ₯Ό ν†΅ν•΄μ„œ μ„œλ²„λ₯Ό λ‚΄λ Έλ‹€κ°€ λ‹€μ‹œ 올렀주면 λ™μž‘ν•œλ‹€.

but. μˆ˜μ •μ‚¬ν•­μ΄ μžˆμ„ λ•Œλ§ˆλ‹€ μ„œλ²„λ₯Ό μ˜¬λ Έλ‹€κ°€ λ‚΄λ €μ£ΌλŠ” λ²ˆκ±°λ‘œμ›€μ€ nodemon으둜 ν•΄κ²°ν•˜μž

728x90
λ°˜μ‘ν˜•

λŒ“κΈ€