JQuery를 사용해 Auto Complete를 사용하고 있었는데, ajax를 사용해서 DB정보에 맞게 가져와야 했습니다.
그래서 ajax를 사용해 구현을 했는데, Auto Complete가 동작하지 않았습니다.
저와 비슷한 문제를 만난 분들을 위해 해결과정을 글로 남겨보겠습니다.
Auto Complete에 대한 자세한 글을 아니니, 해당 내용을 원하신다면
다른 곳에 자세한 설명과 구현방법이 있으니 참고 부탁드립니다.
ajax를 사용한 Auto Complete
Auto Complete를 위한 JQuery 입니다.
$('#loginId').autocomplete({
source : function(request, response) {
$.ajax({
type : 'get',
url: '/auto/username',
dataType : 'json',
success : function(data) {
// 서버에서 json 데이터 response 후 목록 추가
console.log(data);
response(
$.map(data, function(item) {
if (item.startsWith(request.term)) {
return {
label : item
}
}
})
);
}
}
});
ajax통신을 위한 api입니다.
@GetMapping("/auto/username")
public String username() {
return new Gson()
.toJson(userService.findAll()
.stream()
.map(User::getUsername)
.collect(Collectors.toList()));
}
문제
제 코드에서 문제는 ajax 통신할때 발생했습니다.
ajax 통신을 위해 만든 api가 SecurityInterceptor에 걸렸기 때문입니다.
이 문제는 ajax의 error라는 함수를 사용해 알게 되었습니다.
$('#loginId').autocomplete({
source : function(request, response) {
$.ajax({
type : 'get',
url: '/auto/username',
dataType : 'json',
success : function(data) {
response(
$.map(data, function(item) {
if (item.startsWith(request.term)) {
return {
label : item
}
}
})
);
},
error : function (req, textStatus, errorThrown) {
console.log("fail");
console.log(req);
console.log(textStatus);
console.log(errorThrown);
}
});
}
});
error 메서드에 변수로 error 내용을 확인할 수 있었습니다.
해결
AUTO_COMPLETE를 사용하는 api를 interceptor의 통제권에서 제외하고나서 정상작동하는 것을 확인하였습니다.
@Configuration
public class SecurityWebMvcConfig implements WebMvcConfigurer {
public static final String LOGIN_PAGE = "/login";
public static final String JOIN_PAGE = "/join";
public static final String AUTO_COMPLETE = "/auto/**";
public static final String CSS = "/css/**";
public static final String JS = "/js/**";
private final SecurityInterceptor securityInterceptor;
public SecurityWebMvcConfig(SecurityInterceptor securityInterceptor) {
this.securityInterceptor = securityInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(securityInterceptor)
.excludePathPatterns(
CSS,
JS,
AUTO_COMPLETE,
LOGIN_PAGE,
JOIN_PAGE
);
}
}
느낀점
프론트쪽은 더 공부해야 에러를 파악하는데 익숙해질것 같습니다.
'Error' 카테고리의 다른 글
[Error] No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call (0) | 2024.01.07 |
---|---|
[Error] SourceTree와 gitlab SSH키로 연동하기 (0) | 2023.12.19 |