IT Tech/React

JavaScript Fetch와 Spring Boot에서 URL 경로 포함한 DELETE 요청 처리 방법

Developer JS 2024. 7. 11. 14:58
반응형

URL 경로에는 "/" 라던지 "=" 이라던지 "%" 등 여러가지 특수문자가 들어가게 된다. 물론 객체화해서 서버로 보내는 방법도 있다. 하지만 HTTP의 DELETE 메서드로 보낸다면, 어떤 서버는 body 값을 알아서 받아주기도 하지만, SpringBoot의 경우 DELETE 메서드에 body를 포함해서 받으려면 특정한 설정을 해줘야 한다. 그래서 클라이언트 측에서 해당 URL값을 인코딩 처리해서 서버로 보내줘서, 특수문자로 인한 에러가 발생하지 않도로 해줘야 한다.

 

그래서 이미 JavaScript를 만드시는 훌륭한 분들이 간단하게 함수 하나로 해당 URL값을 서버에서 받을 수 있는 인코딩을 쉽게 할 수 있도록 해놓았다. 우리는 그 함수를 사용하기만 하면 쉽게 서버로 전송할 때 에러가 생기지 않게 할 수 있다.

 

URL 인코딩

JavaScript에서 URL을 인코딩하려면 encodeURIComponent 함수를 이용하면된다.

 

const baseUrl = 'http://localhost:8080';
const path = '/images/20240711/248052272847541.png';
const encodedPath = encodeURIComponent(path);

const url = `${baseUrl}${encodedPath}`;

fetch(url, {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json',
  }
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch((error) => console.error('Error:', error));

 

그렇게 해서 그냥 url에 포함해서 전송해주면 끝이다.

 

Spring Boot에서 URL 경로 처리

Spring Boot 컨트롤러에서 URL 경로를 매핑하려면 @PathVariable 어노테이션을 활용하여 경로 매개변수를 처리할 수 있게 된다. 경로가 제대로 인코딩 되면 Spring Boot가 올바르게 디코딩해서 처리할 수 있게 된다.

 

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class MyController {

    @DeleteMapping("/resource/{path}")
    public ResponseEntity<String> deleteResource(@PathVariable String path) {
        // 디코딩된 경로를 사용하여 리소스를 삭제합니다.
        System.out.println("Received delete request for path: " + path);
        
        // 처리 후 응답 반환
        return ResponseEntity.ok("Resource deleted");
    }
}

 

여기서는 @PathVariable 어노테이션을 사용했는데 그냥 @RequestParam을 이용해서 해서 파라미터에 이름을 부여하고, 값을 받아도 된다.

 

const baseUrl = 'http://localhost:8080';
const path = '/images/20240711/248052272847541.png';
const encodedPath = encodeURIComponent(path);

const url = `${baseUrl}?path=${encodedPath}`;

fetch(url, {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json',
  }
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch((error) => console.error('Error:', error));

 

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class MyController {

    @DeleteMapping("/resource")
    public ResponseEntity<String> deleteResource(@RequestParam(name = "path") String path) {
        // 디코딩된 경로를 사용하여 리소스를 삭제합니다.
        System.out.println("Received delete request for path: " + path);
        
        // 처리 후 응답 반환
        return ResponseEntity.ok("Resource deleted");
    }
}

 

 

728x90
반응형