require.js POST请求以发现Web API返回“错误解析json"; [英] require.js POST request to spotify web api returning "Error parsing json"

查看:67
本文介绍了require.js POST请求以发现Web API返回“错误解析json";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Spotify Web API创建播放列表,授权成功后,带有access_token和其他一些参数的POST应该为用户创建一个新的播放列表. 链接

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

这对我来说很好.但是,当我使用request库从nodejs应用程序运行以下代码时,响应状态为Error parsing json.

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.

我在这里想念什么?

更新:我尝试根据request.js示例将data更改为form.我还尝试删除了stringify调用,并直接传递了该对象.该错误仍然存​​在.

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

推荐答案

代替使用data,而使用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);
    });

应该做到的.

这篇关于require.js POST请求以发现Web API返回“错误解析json";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆