使用 GitHub api returns 在 dojo 中执行 PUT 更新 400:解析问题 JSON

Performing a PUT update in dojo using GitHub api returns 400: problems parsing JSON

基本上我正在尝试使用 api 更新 Github 上的文件。当我在 Poster 中执行此操作时,它没有问题,并且我从服务器收到了响应。但是,当在 xhr put 请求中发送完全相同的参数时,我收到 400:错误请求错误 - 解析问题 JSON。这是我的请求:

             var contentArgs = {
                  "message": "Auto TODO commit updating technical debt",
              "committer": {
                "name": "TODO",
                "email": "tododebttracker@gmail.com"
              },
              "content": "bXkgdXBkYXRlZCBmaWxlIGNvbnRlbnRz",
              "sha": "fb617c9e42866ca2446545e0c2725048f6f9530c"
            };
            xhr.put({
            // The URL to request
                url : url,
                headers : {"Authorization" : "token 289543b6aca2454165451a1afcf115fa9a97"},
                content : contentArgs,
                handleAs : "json",
                load : lang.hitch(this,function(result) {
                    deferred.resolve({"hasError" : false,
                           "response": result});
                }),
                error : lang.hitch(this,function(result) {
                    deferred.resolve({"hasError" : true,
                       "response": result });
                })
            });

我已经尝试了 contentArgs JSON 的所有可能变体,我也尝试过在 contentArgs 上使用 JSON.stringify 但没有任何乐趣。任何帮助是极大的赞赏。谢谢

好吧,我假设您正在使用 dojo/_base/xhr(现在还有一个新的 dojo/request/xhr 模块,并且 dojo/_base/xhr 已被弃用)。

这里有一个问题,如果我没记错的话,content 参数应该只用于查询参数。我不能肯定地说,因为该模块可能是所有模块中记录最差的模块之一。

文档说您可能应该使用 data 属性 而不是 content 但我试过了,但也没有解决。

但是,在将 postData 属性 与 JSON.stringify(contentArgs); 一起使用后,它似乎确实有效。所以,试试这个:

xhr.put({
    // The URL to request
    url : url,
    headers : {"Authorization" : "token 289543b6aca2454165451a1afcf115fa9a97", "Content-Type": "application/json"},
    postData : JSON.stringify(contentArgs),
    handleAs : "json",
    load : function() {},
    error : function() {}
});

您可能还应该发送 header Content-Type: application/json 以确保服务器知道它是作为 JSON 字符串发送的。

但是,如果您使用的是 Dojo 1.8+,我建议您使用 dojo/request/xhr。它有一个类似的 API,但它看起来更干净一些(并且也有更好的文档记录):

xhr.put(url, {
    headers : {"Authorization" : "token 289543b6aca2454165451a1afcf115fa9a97", "Content-Type": "application/json"},
    data : JSON.stringify(contentArgs),
    handleAs : "json"
});

这是一个同时使用两者的示例:http://jsfiddle.net/rvnkro8h/ 我删除了一些内容并使用了不同的 URL,但这应该会以 JSON.

的形式谨慎地发送请求负载