๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์‹œ๋„/Code-States

[D+72] ๋‚ด๊ฐ€ ์ดํ•ดํ•œ Node.js

by ๐Ÿ‡๋ฐ•๋ด‰๋ด‰๐Ÿ‡ 2020. 12. 29.

 

D+72

-  ๋‚ด๊ฐ€ ์ดํ•ดํ•œ Node.js -

( Node.js)

 


๐Ÿ˜€ ๊ณต์‹๋ฌธ์„œ๋ฅผ ๋ณด๊ณ  ์ดํ•ดํ•œ ๋ฐฉ์‹๋Œ€๋กœ ์ž‘์„ฑํ•œ ๊ธ€๋กœ ์ •ํ™•ํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค ๐Ÿ˜€

 

 

๊ณต์‹๋ฌธ์„œ๋ฅผ ์ฝ๊ณ  ์•Œ๊ฒŒ๋œ Node.js ๊ฐœ๋…

 

1. Node.js๋ฅผ ํ†ตํ•ด์„œ ์„œ๋ฒ„๋ฅผ ์ƒ์„ฑํ•  ๊ฒฝ์šฐ, ์„œ๋ฒ„๋ฅผ ์ƒ์„ฑํ•˜๊ธฐ ์ „ http๋ชจ๋“ˆ, ํฌํŠธ๋ฒˆํ˜ธ, ip๋ฅผ ์•Œ์•„์•ผ ํ•œ๋‹ค.

 

const http = require('http'); // require์„ ํ†ตํ•ด http ๋ชจ๋“ˆ์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค

const port = 5000; // ํฌํŠธ๋ฒˆํ˜ธ 5000๋ฒˆ

const ip = 'localhost'; // ip๋Š” localhost๋กœ ์„ค์ •

// ex ) http://localhost:5000

 

 

2.  http๋ชจ๋“ˆ๊ณผ createServer๋ฅผ ์ด์šฉํ•ด ์„œ๋ฒ„๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

 

const server = http.createServer((request, response) => {
}) // createServer๋ฅผ ํ†ตํ•ด ์„œ๋ฒ„๋ฅผ ์ƒ์„ฑํ•˜๋Š”๋ฐ ์ด๋•Œ ์š”์ฒญ๊ณผ ์‘๋‹ต์œผ๋กœ ๊ฐ’์„ ์š”์ฒญํ•œ๋‹ค.

 

 

3. listen ๋ฉ”์„œ๋“œ๋Š” ์š”์ฒญ์„ ์‹ค์ œ๋กœ ์ฒ˜๋ฆฌํ• ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

 

server.listen(PORT, ip, () => {
});

 

 

4. request์—” method์™€ url์ด ๋“ค์–ด์žˆ์–ด ์กฐ๊ฑด๋ฌธ์„ ์‚ฌ์šฉํ•  ๋•Œ ์šฉ์ดํ•˜๋‹ค.

 

if(request.method === 'OPTIONS') // ๋งŒ์•ฝ ์š”์ฒญ์˜ ๋ฉ”์„œ๋“œ๊ฐ€ OPTIONS์ผ ๊ฒฝ์šฐ

if(request.method === 'POST' && request.url === '/upper')
// ๋งŒ์•ฝ ์š”์ฒญ์˜ ๋ฉ”์„œ๋“œ๊ฐ€ POST์ด๊ณ  url์ด /upper์ผ ๊ฒฝ์šฐ

 

 

5. ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด์•ผ ํ•œ๋‹ค.

 

6. HTTP ์ƒํƒœ์ฝ”๋“œ๋ฅผ ๋”ฐ๋กœ ์„ค์ •ํ•ด ์ฃผ์ง€ ์•Š์•˜์„ ๊ฒฝ์šฐ ์ƒํƒœ์ฝ”๋“œ๋Š” 200์ด๋‹ค.

 

7. ์ƒํƒœ์ฝ”๋“œ๋ฅผ ๋ณ€๊ฒฝํ•˜๊ณ ์ž ํ• ๋•Œ

 

response.statusCode = 200;

 

 

8. ์ƒํƒœ์ฝ”๋“œ๋„ ์„ค์ •ํ•ด์ฃผ๊ณ  ๋ช…์‹œ์ ์œผ๋กœ ํ—ค๋”๋ฅผ ์ž‘์„ฑํ•˜๊ณ ์ž ํ• ๋•Œ writeHead๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

(CORS๋ฅผ ์ ์šฉํ• ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ๋˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค)

 

9. request์—์„œ ์ด๋ฒคํŠธ๋ฅผ ์„ค์ •ํ•ด์ฃผ๊ณ ์ž ํ• ๋•Œ๋Š” on๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

 

if(request.method === 'POST' && request.url === '/upper') {
  let str;
  request.on('data', chunck => { // on์„ ํ†ตํ•ด 'data'๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.
    str = chunk.toString().toUpperCase();
  }).on('end', () => { // ๋๋‚ด๊ธฐ ์ „ 'end' ์‚ฌ์šฉ
    response.wrtieHead(200, {ํ•ด๋”๊ฐ’});
    response.end(str)
  })
}

 

 

10. response(์‘๋‹ต)์—๋Š” ํ•ญ์ƒ ๋์ด ์žˆ์–ด์•ผ ํ•œ๋‹ค.

 

// end ์‚ฌ์ด์—” ๋‚ด๋ณด๋‚ด๊ณ ์‹ถ์€ ๊ฐ’์„ ์ ์–ด์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋‚ด๋ณด๋‚ด๊ฑฐ๋‚˜, 
// end ์‚ฌ์ด์— ๊ฐ’์„ ์ ์ง€ ์•Š๊ณ  ๊ทธ๋ƒฅ ๋๋‚ผ ์ˆ˜๋„ ์žˆ๋‹ค.

response.end(); 

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€