gpt4 book ai didi

javascript - 在 JavaScript/JQuery 中通过身份验证正确发布数据

转载 作者:行者123 更新时间:2023-11-28 06:12:27 25 4
gpt4 key购买 nike

我正在通过 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);
}
});

最佳答案

要设置 header ,您应该在发送 ajax 请求时使用 header 属性。

// Request with a header property
$.ajax({
url: 'foo/bar',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type':'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",
}),

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

关于javascript - 在 JavaScript/JQuery 中通过身份验证正确发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com