大家好,复活节快乐,
我正在通过 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'd 用于发布。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);
}
});