inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

map undefined 오류 질문드립니다

540

작성자 없음

작성한 질문수 0

1

코드를 혼자 짜보려고 하는 중에 type error:cannot read property 'map' of undefined가 뜹니다. 서버쪽은 postman연동했을때 잘 뜨는데 논리 하자가 있는 것 같습니다..ㅠㅠ뭐가 문제일까요

main/index.js

import "./index.css";
import axios from "axios";
import React from "react";

import { API_URL } from "../config/config.js";

function MainPage() {
  const [products, setProducts] = React.useState([]);
  React.useEffect(function () {
    axios
      .get(`${API_URL}/products`)
      .then(function (result) {
        console.log("RESULT값:", result);
        const products = result.data.products;
        setProducts(products);
      })
      .catch(function (error) {
        console.log("error발생");
      });
  }, []);

  return (
    <div>
      <div id="banner">
        <img src="images/banners/banner1.png" />
      </div>
      <h1>판매되는 상품들</h1>
      <div id="product-list">
        {products.map(function (product, index) {
          return (
            <div className="product-card">
              <div>
                <div className="product-contents">
                  <span className="product-name">{product.name}</span>
                  <span className="product-price">{product.price}</span>
                  <div classNmae="product-footer">
                    <div className="product-seller">
                      <img
                        className="product-avatar"
                        src="images/icons/avatar.png"
                      />
                      <span>{product.seller}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
####App.js

export default MainPage;
import "./App.css";
import MainPageComponent from "./main";

function App() {
  return <MainPageComponent />;
}

export default App;
##server
const express = require("express");
const cors = require("cors");
const app = express();
const port = 7070;
const models = require("./models");

app.use(express.json());
app.use(cors());

app.get("/products", (req, res) => {
  models.Product.findAll({
    attributes: ["id", "name", "price", "imageUrl", "seller", "createdAt"],
  })
    .then((result) => {
      console.log("RESULT값 :", result);
      res.send({
        product: result,
      });
    })
    .catch((error) => {
      console.error("ERROR가 발생하였습니다: ", error);
    });
});

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

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

답변 2

0

그랩

서버에서는 response로 {product: ...}를 전달해주는데, client에서는 result.data.products 로 받네요ㅎㅎ

서버의 response코드에서 product를 products로 이름을 맞춰주시면 해결될 것 같아요! ㅎㅎ

초반에 변수명을 헷갈리는 게 지극히 정상이니 킵고잉 하시길 💪💪

0

ililil

ㅠㅠㅠㅠㅠ이런 멍청한 짓을,,,감사합니다~!

0

그랩

서버에서 찍히는 로그와 클라이언트(브라우저 -> 개발자도구 -> 콘솔 창) 로그를 올려주시면 빠르게 확인할 수 있을 것 같습니다~! 

현재 문제는 클라이언트가 서버에게 제대로 데이터를 받아오지 못했을 때 생기는 이슈입니다! 서버 클라이언트 모두 console.log로 로그로 남겼으니 result에 제대로 값이 들어오는지 확인해보면 좋을 것 같아요.

console.log("RESULT값 :", result);

0

ililil

한번 더 봐주실 수 있을까요?이상하게 result랑 에러가 같이 뜹니다....ㅋㅋ포스트맨도 정상작동됩니다..

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

0

192

2

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

0

165

2

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

0

139

2

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

0

163

2

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

0

120

2

Ngrok 설치 후 forwarding Url 에러

0

148

2

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

0

252

2

Ngrok 설치 후 forwarding Url로 연결 불가

0

158

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

95

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

252

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