HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
💌
JJong’s Archive
/
🌞
JS
/
response.json() vs Response.json(data)

response.json() vs Response.json(data)

Status
Done
Tags
날짜
Jan 14, 2025 06:30 AM
  1. response.json()
      • Fetch API의 Response 객체에서 제공하는 메서드입니다.
      • HTTP 응답(Response)의 body를 JSON 형식으로 파싱하여 JavaScript 객체(promise로 감싸짐)로 반환
      • 이 메서드는 비동기적으로 작동하며, Promise를 반환
      • 내부적으로 응답 본문을 한 번만 읽을 수 있으므로, 다른 방식으로 응답 데이터를 읽으려면 별도의 처리가 필요
        • ex)
          fetch('https://api.example.com/data') .then(response => response.json()) // JSON 데이터를 JavaScript 객체로 변환 .then(data => console.log(data)) // 변환된 데이터 사용
 
  1. Response.json(data)
      • Fetch API에서 제공하는 정적(static) 메서드로, 새로운 Response 객체를 생성
      • 주어진 데이터를 JSON 문자열로 변환해 응답 본문(body)에 저장
      • HTTP 헤더에 Content-Type: application/json을 자동으로 추가합니다.
        • ex)
          const jsonResponse = Response.json({ message: "Hello, World!" }); console.log(jsonResponse); // Response 객체 생성