require.js POST request to spotify web api returning “Error parsing json”

只愿长相守 提交于 2019-12-23 16:46:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!