WEB/Spring Boot
7. Fetch API () 사용하기
마파_
2022. 8. 9. 19:18
기본적인 요청은 아래와 같이 전달할수 있으며, data에는 서버로부터 전달받은 Response의 json Data가 포함 된다.
fetch('http://HOSTDOMAIN/test_request')
.then((response) => response.json())
.then((data) => console.log(data));
Spring boot server에서는 위 요청을 받았을 때, 아래와 같이 json 구조로 response 하게 되어 있다.
@RequestMapping(value = "/test_request", method=RequestMethod.GET)
public ResponseEntity<String> test_request(){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("TestData", "HELLO");
String jsonStr = gson.toJson(jsonObject);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Expires", "0");
return ResponseEntity.ok()
.headers(headers)
.contentLength(jsonStr.length())
.contentType(MediaType.parseMediaType("application/json"))
.body(jsonStr);
}
위의 방법으로 HTML page에서 javascript를 통해 json data를 서버로부터 전달받을 수 있다.