본문 바로가기
타입스크립트로 함께하는 웹 풀 사이클 개발(React, Node.js)/TIL

웹풀사이클 12일차 - express 사용하기

by 슈크림 붕어빵 2023. 12. 7.

http vs express

 

http는 웹 서버 역할을 할 수 있게 만든 내장 모듈

express는 안에 http의 기능이 포함되어 있으며, 좀 더 간결하게 작성할 수 있다.

let http = require("http");

function onRequest(request, response) {
  response.writeHead(200, { "Content-Type": "text/html" });
  response.write("hello node.js");
  response.end();
}

http.createServer(onRequest).listen(8888);

 

=>http일 때보다 express가 조금 더 간편하다.

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

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(3000)

express 사용하기

npm i express

 => node_modules에 설치된다.

 

이렇게 외부 모듈을 설치 후, require로 불러서 사용한다.

 

 

객체, json을 보내는 이유

app.get('/products/1',function(req,res){
  res.send('node.js를 배워보자 (책)');
  res.send(20000);
})

=> 이렇게 보내면 두번째 send는 가지 않기 때문에 객체로 보내야한다.

 

javascript object notation

: 자바스크립트 객체가 어떻게 생겼나 = 어떤 형태인가

 

express에서 url 파라미터 받기

 

/products/:n

 

const express = require("express");
const app = express();

app.listen(3003);

app.get(`/products/1`, function (req, res) {
  res.json({
    num: 1,
  });
});
app.get(`/products/2`, function (req, res) {
  res.json({
    num: 2,
  });
});
app.get(`/products/3`, function (req, res) {
  res.json({
    num: 3,
  });
});

 

=> 줄이기 (url에서 파라미터 받고 사용하기)

const express = require("express");
const app = express();

app.listen(3003);

app.get(`/products/:n`, function (req, res) {
  //products/__빈칸에 오는 값을 n에 담아준다.
  //: => 어? 나한테 url로 매개변수를 전달해줄 것이다.
  //req.params에 모든 것을 담아준다.
  res.json({
    num: req.params.n,
  });
});