Ionic Spotify令牌返回错误415Angular

hvvq6cgz  于 2023-08-01  发布在  Ionic
关注(0)|答案(2)|浏览(137)

我想从Spotify API获取访问令牌,以下是我的请求:

this.http.post("https://accounts.spotify.com/api/token", {
      headers: { 
        'Authorization' : "Basic " + CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse("ID:Secret")),
        'Content-Type':'application/x-www-form-urlencoded'
      },
      params: {
        grant_type : "authorization_code",
        code : code,
        redirect_uri : "REDIRECT URL"
      }
    }).subscribe(data => {
        console.log(data)
    })

字符串
我在控制台中得到这个错误:
https://accounts.spotify.com/api/token的Http失败响应:415 OK

sirbozc5

sirbozc51#

我认为你必须先用参数创建一个HttpParams对象,比如:

let httpParams = new HttpParams()
    .append("grant_type", "authorization_code")
    .append("code", "code")
    .append("redirect_uri", "redirect_uri");

this.http.post("https://accounts.spotify.com/api/token", httpParams.toString(), {
      headers: { 
        'Authorization' : "Basic " + CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse("ID:Secret")),
        'Content-Type':'application/x-www-form-urlencoded'
      }
    }).subscribe(data => {
        console.log(data)
    })

字符串

xxe27gdn

xxe27gdn2#

我知道这是一个古老的问题,但如果有人在寻找解决方案:
这是我最后的工作:

getToken(){
   const client_id = env.SPOTIFY_CLIENT_ID; 
   const client_secret = env.SPOTIFY_CLIENT_SECRET; 
   const url = 'https://accounts.spotify.com/api/token';
   const encoded = btoa(client_id + ':' + client_secret);

   const headers = new HttpHeaders({
     'Content-Type': 'application/x-www-form-urlencoded',
     'Authorization': `Basic ${encoded}`
   });

   const httpParams = new HttpParams()
   .set('grant_type', 'client_credentials')

   return this.http.post(url, httpParams , {headers : headers}).pipe(
     map(res => {
       let data = res
       return data;
     })
   )  
  }

字符串

相关问题