관리 메뉴

프로그래밍 삽질 중

[React] axios error request failed with status code 500 해결 본문

과거 프로그래밍 자료들/컴퓨터설정&오류

[React] axios error request failed with status code 500 해결

평부 2022. 5. 20. 20:12

 

* client의 값을 server로 전송하는 과정에서 생긴 오류

* 참고한 블로그 : (https://velog.io/@kaitlin_k/axios-patch-400-%EC%98%A4%EB%A5%98)

* 오류 원인 : body로 전달할 때 값과 전달받는 값의 형식이 동일해야 했음,

또한 useState의 값을 전달해야하는데 변수값을 전달해서 생긴 오류

 

 

수정 전(Client/UploadProductPage)

 

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

function UploadProductPage(props) {
  const [Continent, setContinent] = useState(1);


  //Fileupload에 있는 것을 새로운 이미지를 받아오도록 함
  const updateImages = (newImages) => {
    setImages(newImages);
  };

  const submitHandler = (event) => {
    //페이지 자동 리프레시 되는 것 막음
    event.preventDefault();

    //값을 다 채우면 서버 request로 보낸다
    const body = {
      continents: Continents, //이 부분이 문제
    };

    axios.post("/api/product", body).then((response) => {
      if (response.data.success) {
        alert("상품 업로드에 성공했습니다.");
        navigate("/");
      } else {
        alert("상품 업로드에 실패했습니다.");
      }
    });
  };

  return (

        <Form onSubmitCapture={submitHandler}>
          <select onChange={continentChangeHandler} value={Continent}>
            {Continents.map((item) => (
              <option key={item.key} value={item.key}>
                {item.value}
              </option>
            ))}
          </select>
          <br />
          <br />
          <Button onClick={submitHandler}>확인</Button>
        </Form>
      </div>
    </div>
  );
}

export default UploadProductPage;

 

 

수정 후(Client/UploadProductPage)

 

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

function UploadProductPage(props) {
  const [Continent, setContinent] = useState(1);


  //Fileupload에 있는 것을 새로운 이미지를 받아오도록 함
  const updateImages = (newImages) => {
    setImages(newImages);
  };

  const submitHandler = (event) => {
    //페이지 자동 리프레시 되는 것 막음
    event.preventDefault();

    //값을 다 채우면 서버 request로 보낸다
    const body = {
      continents: Continent //useState값을 가져옴
    };

    axios.post("/api/product", body).then((response) => {
      if (response.data.success) {
        alert("상품 업로드에 성공했습니다.");
        navigate("/");
      } else {
        alert("상품 업로드에 실패했습니다.");
      }
    });
  };

  return (

        <Form onSubmitCapture={submitHandler}>
          <select onChange={continentChangeHandler} value={Continent}>
            {Continents.map((item) => (
              <option key={item.key} value={item.key}> //key값을 통해 select값 바뀜(Number)
                {item.value}
              </option>
            ))}
          </select>
          <br />
          <br />
          <Button onClick={submitHandler}>확인</Button>
        </Form>
      </div>
    </div>
  );
}

export default UploadProductPage;

 

 

* 서버에서 받는 스키마

 

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const productSchema = mongoose.Schema( {
continents: { 
      type: Number, //key값으로 제어하기 때문에 Number로 지정
      default: 1,
    },
      //시간 자동 업데이트
},  { timestamps: true }
);

const Product = mongoose.model("Product", productSchema);

module.exports = { Product };