본문 바로가기

JavaScript

Node.js 입문 주차 1주차_3

728x90

Node.js 입문 주차 1주차_3


Express.js란?

Node.js로 서버를 빠르고 간편하게 만들 수 있게 도와주는 웹 프레임워크

 

npm install -y

npm install -y

npm install express

 

📄 app.js

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

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

app.listen(port, () => {
  console.log(port, '포트로 서버가 열렸어요!');
});

 

express.js 서버 실행
Thunder Client 설치

 

GET test

GET

 

collections


router

클라이언트 요청을 쉽게 처리할 수 있는 기능 중 하나.

 

 

ctrl + Router

 

📄routes/goods.js

const express = require("express");
const router = express.Router();

// localhost:3000/api/
router.get('/', (req, res) => {
    res.send("default url for goods.js GET Method");
})

// localhost:3000/api/about
router.get('/about', (req, res) => {
    res.send("goods.js about PATH");
});

module.exports = router;

 

📄 app.py

const express = require('express');
const app = express();
const port = 3000;
const goodsRouter = require('./routes/goods.js') //경로

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

// localhost:3000/api -> goodsRouter
app.use("/api", goodsRouter);

app.listen(port, () => {
  console.log(port, '포트로 서버가 열렸어요!');
});

 

router


module

 

📄 modules/math.js

function add(a, b) {
    return a + b;
}

// 모듈 그 자체에 바로 add 함수를 할당한다.
module.exports = add;

 

📄 modules/run.js

const add = require("./math.js")

console.log(add(10, 30));

 

터미널

cd modules
ls
node run.js

 


📄 modules/math.js

// 모듈을 호출했을 때, add 키 값에는 (a,b){return a+b;} 익명함수가 할당되는 방법

exports.add = function (a, b) {
    return a + b;
}

 

📄 modules/run.js

const {add} = require("./math.js")

console.log(add(10,30));

📄 modules/math.js

function add (a, b) {
    return a + b;
}

// 모듈을 호출했을 때, add 키 값에는 add 함수가 들어가는 방법
module.exports = { add : add};

 

📄 modules/math.js

const add = (a,b) => {
    return a + b;
}

exports.add = add;

 

 

📄 modules/run.js

const {add} = require("./math.js")

console.log(add(10,30));

req, res

 

📄 app.py

app.use(express.json());

app.get("/:id", (req, res) => {
  console.log(req.params);

  res.send(":id URI에 정상적으로 반환되었습니다.");
})


app.get("/", (req,res) => {
  console.log(req.query);

  const obj = {
    "KeyKey" : "value 입니다.",
    "이름입니다.":"이름일까요?"
  }

  res.status(400).json(obj);
})

 

id키값에 helloword 반환


📄 app.py

app.use(express.json());

app.post("/", (req,res) => {
  console.log(req.body);

  res.send("기본 URI 에 POST 메소드가 정상적으로 봔환되었습니다.")
})

post body


API

Application Programming Interface

애플리케이션끼리 연결해주는 매개체이자 약속

 

프론트엔드에서 원하는 기능을 수행하는 URL과 인터페이스를 제공한다.

원하는 데이터를 받아 데이터베이스에 데이터를 저장하고,

저장되어 있는 데이터를 읽어서 어플리케이션에 데이터를 제공하는 행위를 통해

사용자가 원하는 목적을 이룰 수 있게 해야 한다.

 


REST API

Representational State Transfer

 

REST API


상품목록 조회 API

  • /goods
  • GET
  • (DB 사용하지 않기 때문에) routes폴더에 goods.js 파일에 json 데이터를 저장

 

📄 /routes/goods.js

// /routes/goods.js

const express = require("express");
const router = express.Router();

const goods = [
    {
      goodsId: 4,
      name: "상품 4",
      thumbnailUrl:
        "https://cdn.pixabay.com/photo/2016/09/07/02/11/frogs-1650657_1280.jpg",
      category: "drink",
      price: 0.1,
    },
    {
      goodsId: 3,
      name: "상품 3",
      thumbnailUrl:
        "https://cdn.pixabay.com/photo/2016/09/07/02/12/frogs-1650658_1280.jpg",
      category: "drink",
      price: 2.2,
    },
    {
      goodsId: 2,
      name: "상품 2",
      thumbnailUrl:
        "https://cdn.pixabay.com/photo/2014/08/26/19/19/wine-428316_1280.jpg",
      category: "drink",
      price: 0.11,
    },
    {
      goodsId: 1,
      name: "상품 1",
      thumbnailUrl:
        "https://cdn.pixabay.com/photo/2016/09/07/19/54/wines-1652455_1280.jpg",
      category: "drink",
      price: 6.2,
    },
  ];

  router.get("/goods", (req,res) => {
    res.status(200).json({goods})
  });

  module.exports = router;

상품목록 조회 API


상품상세 조회 API

URL Parameter,  /:goodsId

  router.get("/goods/:goodsId", (req,res) => {
  	// const params = req.params
    // console.log("params", params)
    
    const { goodsId } = req.params;

    let result = null;
    for(const good of goods){
        if( Number(goodsId) === good.goodsId ){
            result = good;
        }
    }

    res.status(200).json({detail: result});
  });

 

📄 filter이용

  router.get("/goods/:goodsId", (req,res) => {
    const { goodsId } = req.params;

    const {result} = goods.filter((good) => good.goodsId === Number(goodsId))

    res.status(200).json({detail: result});
  });

상품상세 조회 API

 

 

'JavaScript' 카테고리의 다른 글

Node.js 입문 주차 1주차_5  (0) 2022.12.14
Node.js 입문 주차 1주차_4  (0) 2022.12.14
Node.js 입문 주차 1주차_2  (0) 2022.12.13
Node.js 입문 주차 1주차  (0) 2022.12.12
Node.js 실무 기초 1주차  (1) 2022.12.12