inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

비전공자를 위한 진짜 입문 올인원 개발 부트캠프

TypeError: Cannot destructure property 'id' of 'req.params' as it is undefined.

3176

yoomzzi

작성한 질문수 1

1

결제하기 구현 강의에서 

코드를 똑같이 따라했는데 포스트맨에서 실행했을 때  계속 

TypeError: Cannot destructure property 'id' of 'req.params' as it is undefined.

이런 오류가 뜨네요 ㅜ

nodejs HTML/CSS react-native 머신러닝 배워볼래요? javascript express tensorflow react

답변 1

1

그랩

서버쪽 전체 소스코드 공유해주실 수 있으실까요~?

0

yoomzzi

const express = require("express");
const cors = require("cors");
const app = express();
const models = require("./models");
const multer = require("multer");
const upload = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, "uploads/");
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname);
    },
  }),
});
const port = 8080;

app.use(express.json());
app.use(cors());
app.use("/uploads", express.static("uploads"));

app.get("/banners", (req, res) => {
  models.Banner.findAll({
    limit: 2,
  })
    .then((result) => {
      res.send({
        banners: result,
      });
    })
    .catch((error) => {
      console.error(error);
      res.status(500).send("에러가 발생했습니다");
    });
});

app.get("/products", (req, res) => {
  models.Product.findAll({
    order: [["createdAt", "DESC"]],
    attributes: [
      "id",
      "name",
      "price",
      "createdAt",
      "seller",
      "imageUrl",
      "soldout",
    ],
  })
    .then((result) => {
      console.log("PRODUCTS :", result);
      res.send({
        products: result,
      });
    })
    .catch((error) => {
      console.error(error);
      res.status(400).send("에러 발생");
    });
});

app.post("/products", (req, res) => {
  const body = req.body;
  const { name, description, price, seller, imageUrl } = body;
  if (!name || !description || !price || !seller || !imageUrl{
    res.status(400).send("모든 필드를 입력해주세요 ");
  }
  models.Product.create({ description, price, seller, imageUrl, name })
    .then((result) => {
      console.log("상품 생성 결과 :", result);
      res.send({
        result,
      });
    })
    .catch((error) => {
      console.error(error);
      res.status(400).send("상품 업로드에 문제가 발생했습니다");
    });
});

app.get("/products/:id", (req, res) => {
  const params = req.params;
  const { id } = params;
  models.Product.findOne({
    where: {
      id: id,
    },
  })
    .then((result) => {
      console.log("PRODUCT :", result);
      res.send({
        product: result,
      });
    })
    .catch((error) => {
      console.error(error);
      res.status(400).send("상품 조회에 에러가 발생했습니다");
    });
});

app.post("/image", upload.single("image"), (req, res) => {
  const file = req.file;
  console.log(file);
  res.send({
    imageUrl: file.path,
  });
});

app.post("/purchase/:id", (res, req) => {
  const { id } = req.params;
  models.Product.update(
    {
      soldout: 1,
    },
    {
      where: {
        id,
      },
    }
  )
    .then((result) => {
      res.send({
        result: true,
      });
    })
    .catch((error) => {
      console.error(error);
      res.status(500).send("에러가 발생했습니다.");
    });
});

app.listen(port, () => {
  console.log("그랩의 쇼핑몰 서버가 돌아가고 있습니다.");
  models.sequelize
    .sync()
    .then(() => {
      console.log("DB 연결 성공!");
    })
    .catch((err) => {
      console.error(err);
      console.log("DB 연결 에러ㅠ");
      process.exit();
    });
});

0

yoomzzi

강사님이 올려주신 코드를 복사해서 실행 했을땐 제대로 실행되는데,

제가 작성한 코드가 뭐가 잘못됐는지 도저히 모르겠네요 ㅜ 

0

그랩

app.post("/purchase/:id", (res,req) => { 코드를 보시면  (res, req)로 되어있습니다. 보통 순서는 request가 첫번째로 response가 2번째로 오기 때문에 req, res로 적어주셔야 합니다:)

0

yoomzzi

답변 감사합니다!

[해결]그랩님 답변 주세요.

0

190

2

그랩님의 답변을 기다립니다/102강 전반적인 에러

0

162

2

[그랩님께]101강 안드로이드 에러들(Key prop)해결방법 궁금합니다.

0

139

2

[재질문][그랩님 답변 부탁드립니다]101강

0

162

2

[그랩님 답변 부탁드립니다]101강 Axios 에러와 502 Bad Gateway 질문

0

119

2

Ngrok 설치 후 forwarding Url 에러

0

145

2

[그랩님께,Ngrok 악성코드 인식 해결방법]질문 드립니다.

0

251

2

Ngrok 설치 후 forwarding Url로 연결 불가

0

157

1

그랩님,[꼭] 답변 부탁드립니다.

0

76

1

[꼭][[꼭] 그랩님, 답변 부탁드립니다], Failed to load resource: the server responded with a status of 404 (Not Found) 상품 상세 페이지 질문입니다.

0

162

1

6강/7강 수업

0

56

1

그랩님, 상품 상세 페이지 에러와 의문점 질문드립니다.

0

105

2

그랩님, 해결되지 않은 에러 메시지 [꼭] 답변 부탁 드립니다.

0

148

2

[재 질문]Cannot read properties of undefined (reading 'map') TypeError: Cannot read properties of undefined (reading 'map') 에러 해결 어떻게 하나요?

0

94

1

Cannot read properties of undefined (reading 'map') TypeError: Cannot read properties of undefined (reading 'map') 에러 해결 어떻게 하나요?

0

134

2

일반적인 css 꾸미기에서 width와 height의 값?

0

98

2

Windows에서의 업로드 후 홈화면 상품이미지 오류 해결방법

0

204

1

그랩마켓 웹화면 구현하기 -2 질문입니다.

0

127

1

react에 반영이 되지 않습니다.

0

250

1

터미널 npm install -g create-react-app 작성 후 오류

0

430

1

create-react-app my app 실행 시 에러

0

358

2

포스트맨 질문

0

105

1

<꼭 답변 부탁 드립니다>그랩선생님, [컴포넌트 사용하기] 강의에서 질문 있습니다.

0

269

2

그랩선생님, 질문 답변 부탁 드립니다.vscode에서 npm install -g create-react-app 입력 후 에러 입니다.

0

492

2