• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

썜 급해요!

20.04.28 20:12 작성 조회수 154

0

강의를 두세번 돌려봤는데요.

uploadProductPage.js에서 맨 하단에

<Form onSubmit={submitHandler}>
<Button type="submit">확인</Button>

이렇게 하셨는데요. 확인버튼에 onClick를 안해주셔도되는건가요? 실제로 테스트해보니까 저는 확인버튼을 누르면 아무 동작도 일어나지 않아요.

강사님 깃허브 코드 참고해봤는데 강사님꺼는

<Button onClick={onSubmit}>Submit</Button>;

이렇게 되어있네요.

똑같이 따라해봤는데요, 

모든 값을 안넣어주고 확인을 누르면 alert는 잘 나오는데,

제대로 값을 넣어주고 확인을 넣어주면 400 에러가 나옵니다.

이 밖에도 server > models > Product.js 파일에서 

    continents: {
      type: Number,
      default: 1,
   },

위의 코드도 이번 강의에서 찾아볼수없고, 강사님 깃허브 코드에는 있습니다. ㅠ 이번 강의에서 없는건 맞는건지 궁금합니다..

그리고 강의 코드와 제 코드를 아무리 비교해봐도 400에러 발생지를 못찾겠는데.. 도움좀 부탁드릴께요 ㅠㅠ

UploadProductPage.js

import React, { useState } from "react";
import { TypographyButtonFormInput } from "antd";
import FileUpload from "../../utils/FileUpload";
import Axios from "axios";

const { TextArea } = Input;

const Continents = [
  { key: 1value: "Africa" },
  { key: 2value: "Europe" },
  { key: 3value: "North America" },
  { key: 4value: "South America" },
  { key: 5value: "Australia" },
  { key: 6value: "Australia" },
  { key: 1value: "Antarctica" },
];

function UploadProductPage(props) {
  const [TitlesetTitle] = useState("");
  const [DescriptionsetDescription] = useState("");
  const [PricesetPrice] = useState(0);
  const [ContinentsetContinent] = useState(1);
  const [ImagessetImages] = useState([]);

  const titleChangeHandler = (event=> {
    setTitle(event.currentTarget.value);
  };

  const descriptionChangeHandler = (event=> {
    setDescription(event.currentTarget.value);
  };

  const priceChangeHandler = (event=> {
    setPrice(event.currentTarget.value);
  };

  const continentChangeHandler = (event=> {
    setContinent(event.currentTarget.value);
  };

  const updateImages = (newImages=> {
    setImages(newImages);
  };

  const submitHandler = (event=> {
    event.preventDefault();

    if (!Title || !Description || !Price || !Continent || !Images) {
      return alert("모든 값을 넣어주셔야 합니다.");
    }

    // 서버에 채운 값들을 request로 보낸다.

    const body = {
      // 로그인 된 사람의 ID
      writer: props.user.userData._id,
      title: Title,
      description: Description,
      price: Price,
      images: Images,
      continents: Continents,
    };
    Axios.post("/api/product"body).then((response=> {
      if (response.data.success) {
        alert("상품 업로드에 성공 했습니다.");
        props.history.push("/");
      } else {
        alert("상품 업로드에 실패 했습니다.");
      }
    });
  };

  return (
    <div style={maxWidth: "700px"margin: "2rem auto" }}>
      <div style={textAlign: "center"marginBottom: "2rem" }}>
        <h2>여행 상품 업로드</h2>
      </div>

      <Form onSubmit={submitHandler}>
        {/*Drop-Zone */}
        <FileUpload refreshFunction={updateImages} />

        <br />
        <br />
        <label>이름</label>
        <Input onChange={titleChangeHandler} value={Title} />
        <br />
        <br />
        <labe>설명</labe>
        <TextArea onChange={descriptionChangeHandler} value={Description} />
        <br />
        <br />
        <labe>가격($)</labe>
        <Input type="number" onChange={priceChangeHandler} value={Price} />
        <br />
        <br />
        <select onChange={continentChangeHandler} value={Continent}>
          {Continents.map((item=> (
            <option key={item.key} value={item.key}>
              {item.value}
            </option>
          ))}
        </select>

        <br />
        <br />

        <Button type="submit" onClick={submitHandler}>
          확인
        </Button>
      </Form>
    </div>
  );
}

export default UploadProductPage;

routes>product.js

const express = require("express");
const router = express.Router();
const multer = require("multer");
const { Product } = require("../models/Product");

//=================================
//             Product
//=================================
var storage = multer.diskStorage({
  /* 어디에 파일이 저장되는지 */
  destination: function (reqfilecb) {
    cb(null"uploads/");
  },
  /* 어떤 이름으로 파일을 저장할지 */
  filename: function (reqfilecb) {
    cb(null`${Date.now()}_${file.originalname}`);
  },
});

var upload = multer({ storage: storage }).single("file");

router.post("/image", (reqres=> {
  // 가져온 이미지를 저장을 해주면 된다.
  upload(reqres, (err=> {
    if (err) {
      return res.json({ success: falseerr });
    }
    return res.json({
      success: true,
      filePath: res.req.file.path,
      fileName: res.req.file.filename,
    });
  });
});

router.post("/", (reqres=> {
  // UploadProductPage.js에서 받아온 정보들을 DB에 넣어 준다.
  const product = new Product(req.body);

  product.save((err=> {
    if (errreturn res.status(400).json({ success: falseerr });
    return res.status(200).json({ success: true });
  });
});

module.exports = router;

답변 4

·

답변을 작성해보세요.

6

안녕하세요 ^^    ㅋ  넵   대륙을 제가 빼먹었어요 ㅠㅠ ㅎㅎㅎ   

이걸 나중에 발견하고 고치게 됩니다   죄송합니다 ㅠㅠ ! 

그리고  button부분은 ~! 

그냥  button 과    ant 디자인에서 가져온 Button 이 있잔아요 ^^ 

그냥 button으로 하면  onSubmit 없이 해도 되지만   

ant design 것으로 하면  onSubmit 넣어 주셔야 합니다 ^^ ! 

이런 궁금증이 생기시면 언제든 질문주세요 ^^ ~

2

andrewlee님의 프로필

andrewlee

2020.04.28

강의 뒷 부분들으시면 모델에 대륙 빼먹은 거는 귀엽게 고치십니다 ㅎㅎㅎ 

그리고 저는 그 코드가 이상하다고 생각해서 좀 고민 해봤는데 button 에 onclick이 없어도 된다고 생각을 해요. 어짜피 form태그에서 제출을 하니까요 저는 이렇게 코드를 작성해도 제출이 정상 동작했습니다. 

                <button type="submit" >
                    확인
                </button>

아마 다른 부분에서 오류가 나는 것 같은데.. .git으로 올려주시면 답변해줄수있을듯합니다

0

kde 님의 프로필

kde

2020.11.30

다이어그램 보고 continents 있길래 미리 타이핑 해 뒀는데 슨생님 빼먹으시는 거 보고 피식ㅎㅎㅎ 대륙 코드 줍줍해가욥ㅎㅎ

0

답변감사합니다.