Search code examples
curlaxiosnestjsspotify

transform a "curl" query into "axios"


I'm trying to call the Spotify API, and it works well with curl, but when I try to do it with axios in my NestJS app, I got an error.

Here is the "curl" command that works and returns my access token :

curl -X "POST" "https://accounts.spotify.com/api/token" \
-d "grant_type=authorization_code" \
-d "code={MY_AUTHORIZATION_CODE}" \
-d "redirect_uri={MY_REDIRECT_URI}" \
-d "client_id={MY_CLIENT_ID}" \
-d "client_secret={MY_CLIENT_SECRET}" \
-d "scope=user-library-read"


response : 
{"access_token":"{MY_ACCESS_TOKEN}","token_type":"Bearer","expires_in":3600,"refresh_token":"{MY_REFRESH_TOKEN}","scope":"user-library-read"}

And I've tried to transform it into an axios request like this :

  @Get('liked-songs')
  async getLikedSongs(@Query('code') code: string) {
    console.log('code : ', code);
    let accessToken;
    const CLIENT_ID = '{MY_CLIENT_ID}';
    const CLIENT_SECRET = '{MY_CLIENT_SECRET}';
    const REDIRECT_URI = '{MY_REDIRECT_URI}';

    const requestBody = {
      grant_type: 'authorization_code',
      code: code,
      redirect_uri: REDIRECT_URI,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: 'user-library-read',
    };

    axios
      .post('https://accounts.spotify.com/api/token', requestBody)
      .then((response) => {
        console.log('Access token:', response.data.access_token);
        accessToken = response.data.access_token;
      })
      .catch((error) => {
        console.error('Error fetching access token:', error);
      });
  }

So my code is correctly displayed in my console, but I have this error :

Error fetching access token: AxiosError: Request failed with status code 415
at settle (/app/node_modules/axios/lib/core/settle.js:19:12)
at IncomingMessage.handleStreamEnd (/app/node_modules/axios/lib/adapters/http.js:585:11)
at IncomingMessage.emit (node:events:531:35)
at endReadableNT (node:internal/streams/readable:1696:12)
at processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'ERR_BAD_REQUEST',


[Nest] 40  - 12/22/2023, 2:53:44 PM   ERROR [ExceptionsHandler] Request failed with status code 401
AxiosError: Request failed with status code 401

Tell me if you want me to provide more informations about the error


Solution

  • Looking your curl it think you can do like this.

    const requestData = {
       grant_type: 'authorization_code',
       code: code,
       redirect_uri: REDIRECT_URI,
       client_id: CLIENT_ID,
       client_secret: CLIENT_SECRET,
       scope: 'user-library-read',
    };
    
    axios.post('https://accounts.spotify.com/api/token', null, {
      params: requestData,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    .then(response => {
      console.log('Access token:', response.data.access_token);
      accessToken = response.data.access_token;
    })
    .catch(error => {
      console.error('Error fetching access token:', error);
    })