MERN stack 업로드

채희태·2022년 8월 9일
0

shop-app의 product를 업로드하며 MERN stack의 업로드 관련 flow를 연습해보았다.

모델 생성

모델을 생성하기 전에 폴더와 파일을 다음과 같이 생성한다.
backend/server/models/Product.js

모델의 스키마를 다음과 같이 생성한다.

import mongoose from 'mongoose'
const Schema = mongoose.Schema;

// Product 에서 사용할 다큐먼트의 스키마를 정의한다.
const productSchema = new Schema({
  title: String,
  price: Number,
  category: String,
  descriptionShort: String,
  descriptionLong: String,
  image: Array,
}, { timestamps: true });

// 스키마를 모델로 변환하여, 보내준다.
const Product = mongoose.model('Product', productSchema);
module.exports = { Product };

서버로 데이터 보내기

클라이언트에서 서버로 데이터를 보내준다.
body에 보낼 데이터 객체를 담아 post로 해당 서버 경로로 보내준다.

import axios from 'axios'

const onFinish = (e) => {
  const body = {
    title,
    price,
    category,
    descriptionShort,
    descriptionLong,
    image,
  };
  axios
    .post("http://localhost:7000/api/product/upload", body)
    .then((res) => {
      if (res.data.success) {
        console.log(res.data);
      } else {
        alert("업로드에 실패했습니다.");
      }
    });
};

서버에 데이터 저장하기

클라이언트에서 전달 받은 데이터를 서버에서 받아 저장한다.

이 때, 미들웨어로 routing 처리를 해준다.
bacend/server/app.js

app.use("/api/product", require("./routes/product"));

Product 모델에 req.body로 데이터를 담아 인스턴스를 생성한 후,
.save() 메서드로 해당 인스턴스를 저장한다.
저장한 데이터를 doc인자로 클라이언트로 보내줄 수 있다.

import express from "express";
import { Product } from "../models/Product";

const router = express.Router();

router.post("/upload", (req, res) => {
  const product = new Product(req.body);
  product.save((err, doc) => {
    if (err) {
      return res.status(400).json({ success: false, err });
    }
    return res.status(200).json({ success: true, doc });
  });
});

module.exports = router;

mongoDB에 저장되어 있는 것을 확인 할 수 있다.
database => cluster => collections

클라이언트 console에서 저장한 데이터를 확인 할 수 있다.


서버에 저장한 데이터 가져오기

서버에 저장한 데이터를 post메서드를 사용해 클라이언트에서 불러온다.
(get메서드를 사용했더니 error가 발생했다.)

import axios from 'axios'

useEffect(() => {
  axios.post("http://localhost:7000/api/product/products").then((res) => {
    if (res.data.success) {
      console.log(res.data);
    } else {
      alert("데이터를 불러오는데 실패했습니다!")
    }
  });
}, []);

서버에서 다음과 같이 데이터를 보내준다.
find메서드로 저장된 데이터를 모두 찾은 후 exec(실행)메서드로 찾은 데이터를 클라이언트로 보내준다.

import express from "express";
import { Product } from "../models/Product";

const router = express.Router();

router.post("/products", (req, res) => {
  const product = new Product(req.body);
  Product.find().exec((err, doc) => {
    if (err) {
      return res.status(400).json({ success: false, err });
    }
    return res.status(200).json({ success: true, doc });
  });
});

module.exports = router;

불러온 데이터를 console로 확인해 볼 수 있다.

profile
기록, 공부, 활용

0개의 댓글