-
OnlineShop 만들기 - 3)업로드 페이지에 onSubmit 기능 만들기NODE.JS 2021. 5. 15. 16:32
업로드 페이지에 제출 기능을 만들어서 페이지를 완성하자.
순서 먼저 프로덕트 모델을 만들자.
models>product.js파일을 만들어준다.
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const productSchema = mongoose.Schema({ writer: { type: Schema.Types.ObjectId, ref:'User' }, title: { type: String, maxlength:50 }, description:{ type:String }, price:{ type:Number, default:0 }, images:{ type:Array,//하나이상의 이미지를 제출하기때문에 여러 이미지를 저장할 수 있어야 한다. default:[] }, continents:{ type:Number,//지역설정 key를 기준으로 저장하기 때문에 type 이 number이다. default:1//key가 1부터 시작하기 때문에 1이 디폴트다 }, sole:{ type:Number, maxlength:100,//최대 100개까지 팔 수 있다. default:0//하나도 못팔면 0부터 시작 }, views:{ type:Number,//몇명이 봤는지 저장, 디폴트는 0명 default:0 } }, {timestamps:true})//시간 저장 const Product = mongoose.model('Product', productSchema); module.exports = { Product }
이제 onsubmit function을 만들자
uploadproductpage에 가서 함수만든다.
const onSubmit = (event) => { event.preventDefault();//페이지 다시 새로고침 하는 것 방지 if (!TitleValue || !DescriptionValue || !PriceValue ||//어느하나라도 작성이 되어있지 않으면 보내지 않을 것이다. !ContinentValue || !Images) { return alert('fill all the fields first!') } const variables = { writer: props.user.userData._id,//리덕스 스테잇을 보면 어떻게 저장되어 있는지 확인가능하다(로그인정보) title: TitleValue, description: DescriptionValue, price: PriceValue, images: Images, continents: ContinentValue, } Axios.post('/api/product/uploadProduct', variables)//정보들을 전해준다.(프로덕트 모델에 맞춰서) .then(response => { if (response.data.success) { alert('Product Successfully Uploaded') props.history.push('/')//성공한다음에 메인 페이지로 이동할 것이다. } else { alert('Failed to upload Product') } }) } <Button onClick={onSubmit} > Submit </Button>
Axios를 날려줬으니 route폴더로 가서 라우트 만든다.
const { Product } = require("../models/Product");//프로덕트 모델을 가지고와서 처리한다. router.get("/uploadProduct", auth, (req, res) => { //save all the data we got from the client into the db const product = new Product(req.body)//새로운 인스턴스에 가져온 정보들 저장 product.save((err)=>{ if(err) return res.status(400).json({success:false, err}) return res.status(200).json({success:true}) }) });
'NODE.JS' 카테고리의 다른 글
OnlineShop 만들기 - 5) Landing Page 만들기 2(loadmore 버튼) (0) 2021.05.15 OnlineShop 만들기 - 4) Landing Page 만들기 1(상품리스트 가져오기) (0) 2021.05.15 OnlineShop 만들기 - 2) 업로드페이지에 dropzone기능과 ondelete 기능 만들기 (0) 2021.05.15 OnlineShop 만들기 - 1)mongoDB연결하고 업로드페이지 만들기 (0) 2021.05.15 ChatBot 만들기 - 5) actions추가하기 (0) 2021.05.15