在JS / JQuery中使用身份验证正确发布数据

时间:2016-03-27 19:29:34

标签: javascript jquery ajax medium.com

大家好,祝复活节快乐,

我正在通过Electron编写一个简单的文本编辑器,将草稿发布到medium.com。他们提供了api及其文档,但我对jquery和js的了解仍然有限。本质上,我使用Ajax将数据发布到中,但收到400错误。我确定这是一个非常愚蠢和简单的东西,但我无法弄明白,所以这里是我写的用于发布数据的代码:

$('.save_draft').click(function(){

    var accessToken = 'xxxxx';

    $.ajax({
        url: "https://api.medium.com/v1/users/" + user.id + "/posts",
        type: 'POST',
        dataType: 'html',
        contentType: "application/json",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Authentication", accessToken)
        },
        data: {
            "title": "Liverpool FC",
            "contentFormat": "html",
            "content": "<h1>Liverpool FC</h1><p>You’ll never walk alone.</p>",
            "canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc",
            "tags": ["football", "sport", "Liverpool"],
            "publishStatus": "draft",
        },
        success: function(data){
            alert(data);
        }
    });

});

现在我提供了accessToken,我只是'xxxxx它发布了。 user.id在开始时收到,我可以确认它是正确的。至于提供的文档,你可以在这里看到它:https://github.com/Medium/medium-api-docs#33-posts但基本上它要求这样:

POST /v1/users/5303d74c64f66366f00cb9b2a94f3251bf5/posts HTTP/1.1
Host: api.medium.com
Authorization: Bearer 181d415f34379af07b2c11d144dfbe35d
Content-Type: application/json
Accept: application/json
Accept-Charset: utf-8
{
 "title": "Liverpool FC",
 "contentFormat": "html",
 "content": "<h1>Liverpool FC</h1><p>You’ll never walk alone.</p>",
 "canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc",
 "tags": ["football", "sport", "Liverpool"],
 "publishStatus": "public"
}

就像我说的那样,我对ajax中的标题缺乏经验而且有点困惑所以任何帮助都会受到赞赏。感谢。

更新的代码:

$.ajax({
        url: "https://api.medium.com:443/v1/users/" + user.data.id + "/posts",
        type: 'POST',
        headers: {
            'Authorization': 'Bearer ' + accessToken,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        data: JSON.stringify({
            "title": "Liverpool FC",
            "contentFormat": "html",
            "content": "<h1>Liverpool FC</h1><p>You’ll never walk alone.</p>",
            "canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc",
            "tags": ["football", "sport", "Liverpool"],
            "publishStatus": "draft",
        }),
        success: function(data){
            alert(data);
        }
    });

2 个答案:

答案 0 :(得分:1)

对于设置标题,您在发送ajax请求时应使用header属性。

// Request with a header property
$.ajax({
    url: 'foo/bar',
    headers: {
        'Authorization': 'Bearer ' + accessToken,
        'Content-Type':'application/json'
    }
});

此外,您在发送之前会先发送stringify您的数据:

data: JSON.stringify({
        "title": "Liverpool FC",
        "contentFormat": "html",
        "content": "<h1>Liverpool FC</h1><p>You’ll never walk alone.</p>",
        "canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc",
        "tags": ["football", "sport", "Liverpool"],
        "publishStatus": "draft",
    }),

但是你的请求也应该是另一个问题。 400错误意味着您没有向服务发送必填字段

答案 1 :(得分:-1)

我遇到了类似的问题(401&#39;不是允许的域&POST响应)并通过在请求中添加一个额外的标头来解决问题:

    String uri = "http://poweranalyzer-skyglover.rhcloud.com/blackouts/";
    URL url = new URL(uri);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    String input = "{\"blackoutDate\":\"2016/05/03\", \"blackoutTime\":\"18:45:36\"}";

    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();

    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();