미니프로젝트/spring

에러메세지 기록 - syntax error unexpected token ' ' doctype ... is not valid json

rewind 2024. 9. 20. 18:11

Spring Security + OAuth2.0 + JWT 기능 적용 후에

 

session 정책을 stateless 설정하게 되어 모든 동작을 비동기로 바꾸는 중에 발생한 에러

 

게시판에서 이미지 추가시 ckeditor를 통해 aws s3에 업로드 되도록 하였는데 비동기 방식으로 업로드가 된다. 게시글 작성 도중 이미지를 올리는 즉시(게시글 등록을 하지 않더라도) aws에 업로드 요청이 가고 업로드가 된다.

→ 여기까지는 시큐리티와 무관한 기존 동작 방식

 

일부 코드 수정 이후 기능 테스트중 게시판에서 이미지를 올리면 syntax error unexpected token ' ' doctype ... is not valid json 이라는 오류가 alert창을 통해 나오고 업로드가 안되서 어디가 잘못 됐나 했었다.(500에러, 서버로 요청이 가지않음)

 

문제 원인 : jwt로 변환 중에 모든 요청에서 헤더값에 토큰을 담아서 보내는 과정에서 발생

파일업로드이기 때문에 multipart/form-data 형식으로 전달되어야 하는데 헤더에서 데이터 타입을 json으로 지정하여 전송했더니 오류가 나왔다. 클라이언트 헤더코드에서 아래 부분을 지우고 해보니 이상없이 작동 완료

"Content-Type": "application/json"
/** 클라이언트 코드, write.js */
ClassicEditor.create(document.querySelector('#content'), editorConfig)
    .then(editor => {
        window.editor = editor;
        editor.plugins.get('FileRepository').createUploadAdapter = loader => {
            return {
                upload() {
                    return loader.file
                        .then(file => {
                            const data = new FormData();
                            data.append('upload', file);

                            const accessToken = localStorage.getItem("access");

                            return fetch('/upload/uploadCK', {
                                method: 'POST',
                                body: data,
                                headers: {
                                    "access": accessToken
                                //  "Content-Type": "application/json" 이걸 지워야함
                                }
                            })
                                .then(response => response.json())
                                .then(responseData => {
                                    beforeImgAddressWrite.push(responseData.url);
                                    return {
                                        default: responseData.url
                                    };
                                });
                        });
                }
            };
        };
    })
    .catch(error => {
        console.error('There was a problem initializing CKEditor:', error);
    });
/** 서버코드 */
@ResponseBody
@PostMapping("/upload/uploadCK")
public Map<String, Object> uploads(MultipartHttpServletRequest request) {
    MultipartFile uploadImg = request.getFile("upload");
    log.info("uploadImg = {}", uploadImg);

    CustomDetails customDetails = (CustomDetails)SecurityContextHolder.getContext()
        .getAuthentication()
        .getPrincipal();
    String id = customDetails.getName();

    try {
        String successURL = this.awsS3FileUploadService.saveFileToS3(uploadImg, id);
        if (successURL == null) {
            throw new Exception("uploadCK failed");
        }
        log.info("successURL = {}", successURL);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uploaded", true);
        map.put("url", successURL);
        map.put("HttpStatus", ResponseEntity.ok(successURL));
        return map;
    } catch (Exception e) {
        e.printStackTrace();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uploaded", false);
        map.put("HttpStatus", new ResponseEntity<>("uploaded_ERR", HttpStatus.BAD_REQUEST));
        return map;
    }
}

 

해결완료