Java Spring

[웹 애플리케이션 개발] WordController 수정, word 정보를 js를 통해 전달하는 API 만들기 (~ing)

pearl.k 2023. 9. 25. 17:40

내가 앞으로 해야 할 일

1. WordController 수정 : 수정하여 word 정보를 주고 받을 수 있도록 mapping이 필요하다. (RESTful API)

@RestController
@RequestMapping("/api/words")
public class WordController {
    
    @Autowired
    private WordService wordService;

    @GetMapping("/{month}/{day}")
    public ResponseEntity<List<Word>> getWordsByMonthAndDay(
        @PathVariable int month,
        @PathVariable int day
    ) {
        try {
            List<Word> words = wordService.findByMonthAndDay(month, day);
            return new ResponseEntity<>(words, HttpStatus.OK);
        } catch (WordNotFoundException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}

 

2. (1번 작업 후) script.js 파일 수정

자바스크립트 파일에 fetch를 추가하여 Java 애플리케이션에서 보낸 keyword 정보를 화면에 띄울 수 있게 한다.

const currentMonth = new Date().getMonth() + 1;
const currentDay = new Date().getDate();

fetch(`/api/words?month=${currentMonth}&day=${currentDay}`)
  .then(response => response.json())
  .then(data => {
    // 데이터를 성공적으로 받았을 때 실행할 코드
    console.log(data);
    // 이후 원하는 처리를 수행할 수 있습니다.
  })
  .catch(error => {
    // 에러가 발생했을 때 실행할 코드
    console.error('데이터를 불러오는 중 에러 발생:', error);
    // 에러 처리 로직을 추가하세요.
  });