将curl查询转换为axios查询

fjaof16o  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(160)

我试图调用Spotify API,它与curl配合得很好,但当我尝试在NestJS应用程序中使用axios时,我得到了一个错误。
下面是“curl”命令,它可以工作并返回我的访问令牌:

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"}

字符串
我试着把它转换成这样一个axios请求:

@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);
      });
  }


所以我的代码在我的控制台中正确显示,但我有这个错误:

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


告诉我,如果你想让我提供更多的信息错误

0mkxixxg

0mkxixxg1#

看你的卷发,你可以这样做。

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);
})

字符串

相关问题