node.js

REST API 개발하기

늘곰's 2023. 8. 27. 21:47

작성한 REST API 

app.js

// app.js

import express from 'express';
import goodsRouter from './routes/goods.js';
import newsRouter from './routes/news.js';

const app = express();
const PORT = 3000; // 서버를 열 때 사용할 포트 번호

// Express에서 req.body에 접근하여, body 데이터를 사용할 수 있도록 설정하는 미들웨어
app.use(express.json()); // json 형태로 서버에 body 데이터를 전달하면  req.body에 데이터를 변환하여 넣어준다.
app.use(express.urlencoded({ extended: true })); //프론트엔드 협업// form content type에서 body 데이터를 전달하면,  req.body에 데이터를 변환하여 넣어준다.

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

// localhost:3000/api -> goodsRouter
// localhost:3000/api -> newsRouter
// 2. 라우터를 등록 합니다.
app.use('/api', [goodsRouter, newsRouter]);
// 1. Express.js의 서버를 엽니다.
app.listen(PORT, () => {
  console.log(PORT, '포트로 서버가 열렸어요!');
});





/* 
// app.js

import express from 'express';
import goodsRouter from './routes/goods.js';

const app = express();
const PORT = 3000;

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

app.use('/api', (goodsRouter));

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

routes 폴더 

goods.js

import express from 'express';

// 익스프레스에 라우터 생성
const router = express.Router();

// /routes/goods.js

const goods = [
    {
      goodsId: 1,
      name: '상품 1',
      thumbnailUrl:
        'https://cdn.pixabay.com/photo/2016/09/07/19/54/wines-1652455_1280.jpg',
      category: 'drink',
      price: 6.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: 3,
      name: '상품 3',
      thumbnailUrl:
        'https://cdn.pixabay.com/photo/2016/09/07/02/12/frogs-1650658_1280.jpg',
      category: 'drink',
      price: 2.2,
    },
    {
      goodsId: 4,
      name: '상품 4',
      thumbnailUrl:
        'https://cdn.pixabay.com/photo/2016/09/07/02/11/frogs-1650657_1280.jpg',
      category: 'drink',
      price: 0.1,
    },
  ];

/* 상품 목록 조회 API */
// 특정 메소드를 조회한다 get
router.get('/goods', (req, res)=>{
    return res.status(200).json({
        goods:goods,
    })
})

/* 상품 상세목록 API */
// localhost:3000/api/goods/:goodsId
router.get('/goods/:goodsId', (req,res) => {
    // 1. 상품의 id 조회하고
    // 2. 상품 id 와 일치하는 데이터를 찾고,
    // 3. 조회된 상품 정보를 ResponseReturn 한다.
    const goodsId = req.params.goodsId;

    const findGoods = goods.find((oneGoods) => oneGoods.goodsId === +goodsId);

    return res.status(200).json({
        goods : findGoods
    });
});

/* 상품등록 API */
// localhost:3000/api/goods/
router.post('/goods', (req,res) =>{
    //1. name , thumbnailUrl, category, price req.body 로 전달받는다
    //2. 해당하는 데이터를 바탕으로 상품을 등록한다.
    //3. 등록된 상품 데이터를 클라이언트에게 반환한다.
    
    // const name = req.body.name;
    // const thumbnailUrl = req.body.thumbnailUrl;
    // const category = req.body.category;
    // const price = req.body.price;

    // 구조분해 할당 
    const {name, thumbnailUrl, category, price } = req.body;
    // 마지막 값에 +1된 goodsId 생성(가져온다)
    const goodsId = goods[goods.length -1].goodsId + 1;

    const goodsItem = {
        goodsId,
        name,
        thumbnailUrl,
        category,
        price,
    }
   

    goods.push(goodsItem);

    return res.status(201).json({goods: goodsItem});

})





export default router;