728x90
프로젝트 진행중 비동기 처리 방식으로 put, delete restapi 요청을 해보고자 한 적이 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
$.ajax({
usr: '/admin/api/updateIsBan',
method: 'PUT',
headers:{
"X-HTTP-Method-Override" : "PUT"
},
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify(data),
success: function(response) {
// 성공적으로 요청을 보낸 경우 처리할 내용
console.log('PUT 요청 성공:', response);
var updatedAttr = isBan ? 'btn-success' : 'btn-danger';
element.className = updatedAttr;
},
error: function(xhr, status, error) {
// 요청이 실패한 경우 처리할 내용
console.error('PUT 요청 실패:', status, error);
}
});
|
cs |
client
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@RestController
@RequestMapping("/admin/api")
public class adminRestController {
@Autowired
private UserInfoService userInfoService;
@PutMapping(value = "/updateIsBan")
public ResponseEntity<?> updateIsBan(@AuthenticationPrincipal UserPrincipal userPrincipal, @RequestParam Map<String,Object> data) {
System.err.println("탑승");
userInfoService.updateIsBan(data);
return ResponseEntity.ok("Data updated successfully");
}
}
|
cs |
문법상 틀려보이는 부분은 없는데, 이유를 모르겠지만 주소를 찾지 못해 405 에러가 발생했다.
아마 굳이 해결방법을 어떻게든 찾는다면 단순히 POST로 바꿔서 보낸다거나 다른 설정을 만지작해서 가능이야 할 수 있겠지만 더 간결하고 표준에 적합한 방법으로 해결하고 싶었다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
fetch('/admin/api/updateIsBan', {
method: 'PUT',
headers: {
'Content-Type': 'application/json', // 요청의 Content-Type 설정
},
body: JSON.stringify(data) // 요청에 포함될 데이터
})
.then(response => {
console.log('PUT 요청 성공:', response);
var updatedAttr = isBan ? 'btn-success' : 'btn-danger';
element.className = updatedAttr;
element.valueOf(isBan);
})
.catch(error => {
console.error('PUT 요청 실패:', status, error);
});
|
cs |
그래서 자바스크립트 ES6의 fetch() API를 써서 더 코드를 줄이고, 간단하게 해결
반응형