我正在通过Electron为一个简单的文本编辑器编写一个应用程序,它可以将草稿发布到Medium.com。他们提供了一个API和文档,但我在jQuery和JavaScript方面的知识仍然有限。本质上,我正在使用 AJAX 将数据发布到Medium,但收到了一个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({
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条答案
按热度按时间wpcxdonn1#
发送ajax请求时,您应该使用
header
属性来设置头。此外,您还应在发送以下内容之前先对数据进行
stringify
:400错误意味着您没有向服务发送必需的字段
rnmwe5a22#
我遇到了类似的问题(POST上的401“is not an allowed domain”响应),并通过在请求中包含一个额外的标头来解决该问题: