axioserror: request failed with status code 401 해결

Chae Eun Kim·2023년 1월 28일

문제상황

node 프로젝트에서 apple music api에 곡 검색 요청을 보내는 axios.get 사용 중에 axioserror: request failed with status code 401 라는 error를 catch하는 문제가 발생했다. 아래는 문제의 코드

const token = 'Bearer ' + config.appleDeveloperToken as string;
        let musiclist: MusicResponseDto[] = [];

        const appleResponse = async (searchKeyword: string) => {
    
            await axios.get('https://api.music.apple.com/v1/catalog/kr/search?types=songs&limit=20&term=' 
                + encodeURI(searchKeyword), {
                    headers: {
                      'Content-Type': 'application/json',
                      'Authorization': token
                    }
                }
            )
            ...

애플뮤직 api 요청 때 사용하는 개발자 토큰을 헤더의 Authorization 키에 Bearer 토큰으로 보내줘야만 하는데 계속 401 unauthorized라는 결과를 애플 api로부터 받았다.
이유는 Bearer과 token을 잇는 방법때문이었다.

해결

Bearer과 token을 백틱(`)을 이용해서 이으니 해결됐다.

// 해결
const token = `Bearer ${config.appleDeveloperToken as string}`;

// 에러        
//const token = 'Bearer ' + config.appleDeveloperToken as string;

0개의 댓글