inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스

포스트맨 실습 진행 시 undefined 오류

해결된 질문

292

ZZAMBA

작성한 질문수 13

0

 같은 코드를 이용해 포스트맨 호출 시, 다음 에러가 발생합니다.

TypeError: Cannot read property 'moneyService' of undefined
    at buyProduct (file:///home/xxx/%EB%B0%94%ED%83%95%ED%99%94%EB%A9%B4/codecamp-backend-online/class/12/12-01-express-with-DI-IoC/mvc/controllers/product.controller.js:11:31)
    at Layer.handle [as handle_request] (/home/xxx/바탕화면/codecamp-backend-online/node_modules/express/router/layer.js:95:5)
    at next (/home/xxx/바탕화면/codecamp-backend-online/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/home/xxx/바탕화면/codecamp-backend-online/node_modules/express/lib/router/route.j4:3)
    at Layer.handle [as handle_request] (/home/xxx/바탕화면/codecamp-backend-online/node_modules/express/router/layer.js:95:5)
    at /home/xxx/바탕화면/codecamp-backend-online/node_modules/express/lib/router/index.js:284:15
    at Function.process_params (/home/xxx/바탕화면/codecamp-backend-online/node_modules/express/lib/routedex.js:346:12)
    at next (/home/xxx/바탕화면/codecamp-backend-online/node_modules/express/lib/router/index.js:280:10)
    at jsonParser (/home/xxx/바탕화면/codecamp-backend-online/node_modules/body-parser/lib/types/json.js:7)
    at Layer.handle [as handle_request] (/home/xxx/바탕화면/codecamp-backend-online/node_modules/express/router/layer.js:95:5)

이 때, app.post 미들웨어 함수 부분에 bind()로 엮어주어야만 정상 작동하는데 이유가 무엇일까요?


코드는 아래 첨부합니다.

import express from "express";
import {ProductController} from "./mvc/controllers/product.controller.js";
import {CouponController} from "./mvc/controllers/coupon.controller.js";
import {CashService} from "./mvc/controllers/services/cash.service.js";
import {ProductService} from "./mvc/controllers/services/product.service.js";
import {PointService} from "./mvc/controllers/services/point.service.js";

const app = express();
app.use(express.json());

const cashService = new CashService();
const productService = new ProductService();
const pointService = new PointService();
// 상품 API
const productController = new ProductController(cashService, productService);
app.post("/products/buy", productController.buyProduct)
app.post("/products/refund", productController.refundProduct)

// 쿠폰 구매하기
const couponController = new CouponController(pointService);
app.post("/coupons/buy", couponController.buyCoupon);

app.listen(3000, () => {
    console.log("3000번 포트에서 연결 중...");
})

index.js

export class ProductController {
    constructor(moneyService, productService) { // DI (IoC)
        this.moneyService = moneyService;
        this.productService = productService;
    }

    buyProduct(req, res){
        // 지불 금액 검증
        const hasMoney = this.moneyService.checkValue();

        // 재고 검증 (재고 있으면 구매)
        const isSoldOut = this.productService.checkSoldOut();

        // 상품 구매 코드
        if (hasMoney && !isSoldOut) {
            res.send("상품 구매 완료");
        }
    }

    refundProduct(req, res){
        // 재고 검증 (재고 없으면 환불) (구매 코드와 중복)
        const isSoldOut = this.productService.checkSoldOut();
        // 환불 코드
        if (isSoldOut)
            res.send("환불 완료");
    }
}

ProuductController

export class CouponController{
    constructor(moneyService) {
        this.moneyService = moneyService;
    }

    buyCoupon(req, res){
        const hasMoney = this.moneyService.checkValue();
        // 쿠폰 구매 코드
        if (hasMoney){
            res.send("쿠폰 구매 완료");
        }
    }
}

CouponController

export class ProductService{
    checkSoldOut(){
        console.log("판매 완료 검증.");
        // 재고 검증
    }
}

ProductService

export class PointService{
    checkValue(){
        console.log("포인트 검증.");
        // 지불 금액 검증
    }
}

PointService

export class CashService{
    checkValue(){
        console.log("현금 검증.")
        // 지불 금액 검증
    }
}

CashService

 

docker node.js nodejs express rest-api javascript tdd NestJS

답변 1

0

angie

안녕하세요. ZZAMBA님

ProuductController 파일 내부 클래스의 method 선언 방식을 확인해 보세요.
이에 관하여 화살표 함수와 this에 대해 검색하셔서 학습해 보시길 바랍니다. 감사합니다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions

0

ZZAMBA

항상 감사합니다.

그래프 ql 문서 사용할때 느낌표 남는거 어떻게 없애나요?

0

86

2

강의 전체 소스 코드를 받고싶습니다.

0

77

2

fontawesome 사용 문의

0

81

2

소스 코드 부탁드립니다~

0

87

2

깃 레포지터리 소스

0

87

2

커리큘럼12.css 정렬 에 나오는 과제 정답알고싶어요

0

74

2

10-01 Entity TypeOrmModule.forRoot 에 entities

0

89

3

강의 버전관련 문의입니다

0

104

2

Ubuntu 설치 관련

0

62

1

schema.gql 질문 드립니다.

0

51

1

서버 재실행시 Many to Many

0

102

3

input 관련 문의

0

90

2

Rest API 보다는 graphql이 주된 내용인데

0

134

2

강의 전체 소스코드 받을수있을까요?

0

156

1

도커볼륨 마운트 관련

0

127

2

findOne 타입스크립트오류

0

109

1

http => htrtps 호출 인증서 신뢰 오류

0

356

1

self-signed certificate in certificate chain 에러 발생

0

421

1

mongoose 설치 오류

0

143

1

특정 API, 특정 IP 허용 (단일경로에 CORS 활성화)

0

286

2

08-06

0

180

3

구조랑 패턴 관련해서 질문

0

126

2

mydocker

0

129

2

coolsms statuscode 2000 인데 전송안돼는 경우 확인.

0

156

1