2017-11-05 4 views
0

스포티 파이 API이 컬 요청은 완벽하게 잘 작동

curl -X "POST" -H "Authorization: Basic <my-key-here>" -d grant_type=client_credentials https://accounts.spotify.com/api/token

내가 노드에서이 작업을 수행하기 위해 노력하고있어,하지만 작동하지 않는 나쁜 400을 반환 의뢰. 여기 내 코드가있다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

function AuthRequest(key) { 

    const req_body_params = JSON.stringify({ 
    grant_type: "client_credentials" 
    }) 

    const base64_enc = new Buffer(key).toString("base64") 

    const options = { 
    host: "accounts.spotify.com", 
    port: 443, 
    path: "api/token", 
    method: "POST", 
    headers: { 
     "Content-Type": "application/json", 
     "Authorization": `Basic ${base64_enc}` 
    } 
    } 

    const req = https.request(options, function (res) { 
    res.on('data', function (data) { 
     alert("success: " + data) 
    }) 
    }) 

    req.on('error', function (err) { 
    alert("error: " + err) 
    }) 

    req.write(req_body_params) 
    req.end() 

} 

여기에 설명 된대로 나는 클라이언트 자격 증명 방법을 사용하려고 해요 : https://developer.spotify.com/web-api/authorization-guide/

+0

무엇이 오류입니까? –

+0

400 잘못된 요청 – user3685285

+0

코드 및 redirect_uri와 같은 필수 매개 변수가 없습니다. – kbariotis

답변

1

는 요청이 대신 JSON의 application/x-www-form-urlencoded에 있어야이 "Content-Type": "application/x-www-form-urlencoded"

function AuthRequest(key) { 
    const req_body_params = "grant_type=client_credentials"; 
    const base64_enc = new Buffer(key).toString("base64"); 

    const options = { 
     host: "accounts.spotify.com", 
     port: 443, 
     path: "/api/token", 
     method: "POST", 
     headers: { 
      "Content-Type": "application/x-www-form-urlencoded", 
      "Authorization": `Basic ${base64_enc}` 
     } 
    }; 

    const req = https.request(options, function(res) { 
     res.on('data', function(data) { 
      alert("success: " + data) 
     }) 
    }); 

    req.on('error', function(err) { 
     alert("error: " + err) 
    }); 

    req.write(req_body_params); 
    req.end(); 
} 
의 헤더와 const req_body_params = "grant_type=client_credentials"을해야한다,
+0

정말이 답변을 원하지만이 코드로 400 개의 잘못된 요청을받습니다. – user3685285

+0

나는 당신이 길을가는 데 선도적 인 슬래시를 놓친 것 같아요? – AngYC

+0

오! 감사! – user3685285

0

토큰이 만료되면 동적으로 요청하는 것이 좋기 때문에 약속으로 토큰을 출력하는 메서드를 만들었고 요청할 때 소비 할 수 있습니다.

const axios = require('axios') 

const client_id = process.env.SPOTIFY_CLIENT_ID; 
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; 

function getToken() { 
    return axios({ 
     url: 'https://accounts.spotify.com/api/token', 
     method: 'post', 
     params: { 
      grant_type: 'client_credentials' 
     }, 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded' 
     }, 
     auth: { 
      username: client_id, 
      password: client_secret 
     } 
    }) 
} 


async function getSpotifyData(endpoint){ 
    const tokenData = await getToken(); 
    const token = tokenData.data.access_token; 
    axios({ 
     url: `https://api.spotify.com/v1/${endpoint}`, 
     method: 'get', 
     headers: { 
      'Authorization': 'Bearer ' + token 
     } 
    }).then(response => { 
     console.log(response.data); 
     return response.data; 
    }).catch(error => { 
     throw new Error(error); 
    }); 
} 
getSpotifyData('browse/new-releases');