본문 바로가기

Typescript & React

SyntaxError: Unexpected end of JSON input

728x90

JSON 데이터를 파싱할 때 발생하는 문제라는 것이 예상이 된다. 요청 또는 반환 값이 json의 형태가 아닐 것이라는 생각으로 추론을 하고 디버깅을 시작했다.  

 

요청

await fetch('http://localhost:3000/order/storegoods', {
      headers:{
        'x-jwt':token,
        'Content-Type': 'application/json; charset=utf-8',
      },
      method:'POST',
      body:JSON.stringify({
        dealId: deal.id,
        customer,
        payment:{
          price:numPrice,   //relation으로 price 여기에 포함되어있고 가져오면됨  
          maintenanceYN,
          maintenance_cost: numManitenance, //{ maintenanceYN: true, maintenance_cost: '100' }
          total:numTotal , //문제: total: ''  빈값 + string 값
        },
      })
    })
  ).json()

 

컨트롤러 

@Post('/storegoods')
  storeGoods(@Req() req: Request){
    const me = req['member'];
    return this.orderService.storeGoods(req.body, me);
 }

 

비즈니스 로직

  • 문제 확인: 반환 값이 JSON 이 아니다. 
  • 따라서 요청의 반환 값을 json 형태로 파싱을 하면 에러가 발생한다. 
async storeGoods(savingInput, me:Member) {

    const dealId = parseInt(savingInput.dealId);
    const oneDeal = await this.deals.findOne({
      where:{
        id: dealId,
      }
    })

    const newStore = this.stores.create({
      member: me,  
      deal: oneDeal,
      payment: savingInput.payment

    })
    await this.stores.save(newStore);
    
  }

 

나의 경우 반환 값이 필요가 없어 다음과 같이 수정했다. 

const savingGoods = await(
    //결제 서비스 추가 가정: 주문 정보 확인 후 -> 결제 요청 -> (카카오, 네이버)페이 앱 연결 -> 결제 승인, 응답 -> order주문: 승인상태 값 등록   

    await fetch('http://localhost:3000/order/storegoods', {
      headers:{
        'x-jwt':token,
        'Content-Type': 'application/json; charset=utf-8',
      },
      method:'POST',
      body:JSON.stringify({
        dealId: deal.id,
        customer,
        payment:{
          price:numPrice,   //relation으로 price 여기에 포함되어있고 가져오면됨  
          maintenanceYN,
          maintenance_cost: numManitenance, //{ maintenanceYN: true, maintenance_cost: '100' }
          total:numTotal , //문제: total: ''  빈값 + string 값
        },
      })
    })
  ).ok  //✅ blooen 형태의 값을 반환 -> ok 값이 true 값을 반환 -> 제품 담기 성공 알림창으로 변경!

 

해결방안

아래와 같이 알림창으로 변경하여 해결하였다. 

상품 담기 성공 알림창

728x90