본문 바로가기
카테고리 없음

에러 해결 -blackListId값 매핑 하지못함

by zkzk7290 2024. 12. 31.
반응형
AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : adapter : (3) ['xhr', 'http', 'fetch'] data : undefined env : {FormData: ƒ, Blob: ƒ} headers : AxiosHeaders {Accept: 'application/json, text/plain, */*', Content-Type: undefined, Authorization: 'Bearer eyJhbGciOiJIUzI1 NiJ9.eyJ1c2 VySWQiOiJja2 NrNz…TIxfQ.cagxldgDzX1I7 ANVPBUoMV2 LPKnDm0 oY3b4 xLsvZ-O4'} maxBodyLength : -1 maxContentLength : -1 method : "delete" timeout : 0 transformRequest : [ƒ] transformResponse : [ƒ] transitional : {silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false} url : "http://localhost:8080/api/v1/black-list/undefined" validateStatus : ƒ validateStatus(status) withCredentials : true xsrfCookieName : "XSRF-TOKEN" xsrfHeaderName : "X-XSRF-TOKEN" [[Prototype]] : Object message : "Request failed with status code 403" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} response : {data: '', status: 403, statusText: '', headers: AxiosHeaders, config: {…}, …} status : 403 stack : "AxiosError: Request failed with status code 403\n at settle (http://localhost:3000/static/js/bundle.js:122637:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:121288:66)\n at Axios.request (http://localhost:3000/static/js/bundle.js:121787:41)\n at async handleDeleteBlackList (http://localhost:3000/main.a9d40173740b57178 ed7.hot-update.js:66:26)" [[Prototype]] : Error constructor : ƒ AxiosError(message, code, config, request, response) toJSON : ƒ toJSON() isAxiosError : true [[Prototype]] :

이 에러의 결론은  blackListId 값을 제대로 전달되지 않아 계속 콘솔에 찍어 보면  undefined라는 값이 뜬다 

+ 403  BadRequest 로 뜬다  

 

그래서 개발자 도구에 들어가서 확인해보면 400 에러 떠서 정말로 많이 곤란했다.

그리고 백+프런트에서 계속 ㅊ출력 코드를 찍어서 봤는데 값이 제대로 안 나와서 정말 힘들었다.

gpt에게 물어보고 했는데 gpt의 대답으로 내가 순간 get로직에 blackListId값을 넣어서 로직을 완성했는지  순간 너무 의심을 들어서 확인하러 갔는데 역시나 넣지 않았다.

@Data
@NoArgsConstructor
@AllArgsConstructor
//dto
public class ResponseGetBlackListDto {
    @NotBlank//따로 추가함 
    private Long blackListId;

    @NotBlank
    private String profileImage;

    @NotBlank
    private String nickName;

    @NotBlank
    private String userLevel;



}
  // 블랙 리스트 조회
    @Override
    public ResponseDto<List<ResponseGetBlackListDto>> getBlackList(Long groupId) {
        List<ResponseGetBlackListDto> data = null;
        try {
            List<Object[]> blackLists = blackListRepository.findByGroup(groupId);
            data = blackLists.stream()
                    .map(result -> new ResponseGetBlackListDto(
                    //reuslt[0]  추가로 넣어서 에러 잡아주면 됩니다 
                            result[1].toString(),
                            result[2].toString(),
                            result[3].toString()
                    ))
                    .collect(Collectors.toList());

            return ResponseDto.setSuccess(ResponseMessage.SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDto.setFailed(ResponseMessage.DATABASE_ERROR);
        }
    }

이렇게 해도 가능합니다  아니면 프런트에서 추가적으로 Id값을 생성해 주는 코드 작성 해주면  가능합니다

 

const fetchBlackList = async () => {
    if (cookies.token) {
      try {
        const response = await axios.get(
          `http://localhost:8080/api/v1/black-list/${groupId}`,
          {
            headers: {
              Authorization: `Bearer ${cookies.token}`,
            },
            withCredentials: true,
          }
        );
        //blackListId 값을 생성해주는 코드 
        const responseData = response.data.data.map((item: any, index: number) => ({
          ...item,
          blackListId: index+1
        }));
        setBlackUserList(responseData);
        console.log("transformed Data : "+ responseData);
      } catch (error) {
        console.error(error);
      }
    }

map으로 새로운 배열을 생성하고 각 항목에 blackListId라는 속성 을 추가한다. 

index+1을 한 이유는 0부터 시작하기 때문에  +1을  해줘서 1을 부터 시작한다

item은 현재 순회하는 항목이고  ...item객체를 그래도 복사하고 새로운 blackListId값을 추가한다

그러니깐 무사히 성공 했다 

반응형