데브코스/강의 정리

3주차 express와 json 객체

케케_ 2024. 8. 30. 23:09

http vs express

express 모듈 안에 http 포함

http: 웹 서버 역할을 하게 만들어줌

 

설치

express 설치: nmp i express

 cf. index.js: 웹 서비스를 만들때 첫 페이지로 쓰이는 이름!

 

 - 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);

 

  • 브라우저

 

 

 - express 사용

  • nmp 사이트의 예제 코드
const express = require("express");
const app = express();

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

app.listen(3000);

 

  • app: express 모듈을 이용해 서버를 받은 변수
  • get: 문자열로 무언가 일을 하고 콜백 함수 호츨
  • '/' = 'http://localhost:3000/'
  • req가 들어오면 res로 대응

 

 - 포트넘버

  • 의미있는 번호로 정하면 좋음
  • 각 회사 체계 - 서비스 번호 

express REST API 실습

express랑 친해지기

 

 - API 실습 1

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

//GET + "/"
app.get("/", function (req, res) {
  res.send("Hello World");
});

// API: GET + "http://localhost:1234/test"
// "TEST SUCCESS"
app.get("/test", function (req, res) {
  res.send("TEST SUCCESS");
});

// API: GET + "http://localhost:1234/test/1"
// "one!!"
app.get("/test/1", function (req, res) {
  res.send("one!!");
});

app.listen(1234);

 

 

 - API 실습 2 응용

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

// GET /hello, /bye, /nicetomeetyou
app.get("/hello", function (req, res) {
  res.send("안녕하세요");
});
app.get("/bye", function (req, res) {
  res.send("안녕히 가세요");
});
app.get("/nicetomeetyou", function (req, res) {
  res.send("만나서 반갑습니다.");
});

app.listen(1234);

 

 - 코드 뜯어보기

  • get 메소드로 '/hello'가 날아오면, 매개변수로 전달받은 콜백함수를 호출하겠어! --> 서버에 셋팅
  • app.listen(1234)
    • 서버셋팅: 포트넘버를 1234로 셋팅

    --> 즉 서버를 setting하는 코드들로 코드의 순서는 상관이 없음!

    (listen 코드가 변수 선언 뒤에 바로 와도 코드는 잘 돌아감)

 

  • express()
    • command 누르고 해당 메소드 클릭하면 그에 대한 코드 확인 가능

  • express는 html의 body 값을 구분함!
  • 우리는 주로 json을 사용할 것

why? 주로 json을 사용하는 이유

  • 위의 실습에선 응답으로 text만 사용함 : res.send(문자열)
  • 실제: 화면에는 텍스트 하나만 존재하는게 아님 (다양한 데이터 덩어리)
app.get("/products/1", function (req, res) {
res.send("Node.js를 배워보자 (책)");
res.send(20000);
});
  • 이 코드를 추가해 돌려보면

  • 요딴 식으로 나옴.... (20000이 나오지 X)

 

  • 그럼 어떻게? "객체"

객체

  • 우리 세상이 객체로 이루어져 있습니다.
  • 주어 자리에 왔을 때 문장이 만들어지면 그건 객체다! by 김송아 강사님
    • 예)
    • "Node.js를 공부해보자. 라는 책 하나의 정보들"
    •  - 상품명: Node.js를 공부해보자.
    •  - 가격: 20000
    •  - 소개: 이 책이 왜 좋은가. ......어쩌구

 

자바스크립트 객체

javascript object notation(json): 자바스크립트 객체는 어떻게 생겼나 = 어떤 형태인가

 

 - 형태

let person = {

  name : "kim",

  age : 20

}

 

 - 위의 책에 대한 객체 만들어 보기

let book = {

  title : "Node.js를 공부해보자." ,

  price : 20000,

  description : "이 책이 왜 좋은가. ......어쩌구"

}

let book = {
  title: "Node.js를 공부해보자.",
  price: 20000,
  description: "이 책이 왜 좋은가. ......어쩌구",
};

console.log(book.title); //Node.js를 공부해보자.
console.log(book.price); //20000
console.log(book.description); //이 책이 왜 좋은가. ......어쩌구

 

  • 객체가 매개변수로 전달됨!
let nodejsbook = {
  title: "Node.js를 공부해보자.",
  price: 20000,
  description: "이 책이 왜 좋은가. ......어쩌구",
};

function print(book) {
console.log(book.title); //Node.js를 공부해보자.
console.log(book.price); //20000
console.log(book.description); //이 책이 왜 좋은가. ......어쩌구
}

print(nodejsbook);

 

  • express 안에서 객체 만들기
const express = require("express");
const app = express();

app.listen(1234);

// GET /hello, /bye, /nicetomeetyou
app.get("/hello", function (req, res) {
  res.send({
    say: "안녕하세요",
  });
});

 

 

  • send: 응답 보내는 메소드, (안에 json 올 수 있음)

 

  • json 이용

  • json 날리기 - 1
const express = require("express");
const app = express();

app.listen(1234);

// GET /hello, /bye, /nicetomeetyou
app.get("/hello", function (req, res) {
res.json({
say: "안녕하세요",
});
});
app.get("/bye", function (req, res) {
  res.json({
    say: "안녕히 가세요",
  });
});

 

  • json 날리기 - 2
app.get("/products/1", function (req, res) {
res.json({
title: "Node.js를 배워보자 (책)",
price: 20000,
description: "이 책이 왜 좋은가. ......어쩌구",
});
});

 

  • json 날리기 - 3: 객체 정의 후 이름으로 넘기기
let nodejsbook = {
title: "Node.js를 공부해보자.",
price: 20000,
description: "이 책이 왜 좋은가. ......어쩌구",
};

app.get("/products/1", function (req, res) {
res.json(nodejsbook);
});

 

  • product/1,2, ...
const express = require("express");
const app = express();

app.listen(1234);

app.get("/products/:n", function (req, res) {
  // : => 어? 나한테 URL로 매개변수를 전달해줄 건 가부다
  // req.params: request에 파라미터를 보겠다
  // produnts/__빈칸에 오는 n이란 값을 변수에 담아줘
  res.json({
    num: req.params.n,
  });
});