问题
According to Spotify Web API Create Playlist, once authorization is successful, a POST with the access_token and a few other parameters should create a new playlist for the user. The example CURL command in the link
curl -X POST "https://api.spotify.com/v1/users/wizzler/playlists"
-H "Authorization: Bearer {your access token}"
-H "Content-Type: application/json" --data "{\"name\":\"A New Playlist\", \"public\":false}"
This working fine for me. But when i run the following code from a nodejs application, using request
library, the response stats Error parsing json
.
What am i missing here?
Update: I tried changing data
to form
as per request.js examples. I also tried removing the stringify call, and passed the object directly. The error still persists.
var request = require('request');
var authOptions1 = {
url: 'https://api.spotify.com/v1/users/' + username + '/playlists',
data: JSON.stringify({
'name': name,
'public': false
}),
dataType:'json',
headers: {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json',
}
};
console.log(authOptions1);
request.post(authOptions1, function(error, response, body) {
console.log(body);
});
回答1:
Instead of using data
, use body
:
var request = require('request');
var authOptions1 = {
url: 'https://api.spotify.com/v1/users/' + username + '/playlists',
body: JSON.stringify({
'name': name,
'public': false
}),
dataType:'json',
headers: {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json',
}
};
request.post(authOptions1, function(error, response, body) {
console.log(body);
});
that should make it.
回答2:
According to https://github.com/mikeal/request#requestoptions-callback
var authOptions1 = {
url: 'https://api.spotify.com/v1/users/' + username + '/playlists',
form: { // data = form
'name': name,
'public': false
},
json: true, // dataType: json = json: true
headers: {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json',
}
};
request.post(authOptions1, function(error, response, body) {
console.log(body);
});
来源:https://stackoverflow.com/questions/24589873/require-js-post-request-to-spotify-web-api-returning-error-parsing-json