我一直在寻找一个纯HTML和jQuery示例,介绍如何使用REST API在Confluence中创建页面。我找到了以下示例,但它们都不适用于我:
示例A
var username = "admin";
var password = "admin";
var jsondata = {"type":"page",
"title":"My Test Page",
"space":{"key":"TST"},
"body":{"storage":{"value":"<p>This is a new page</p>","representation":"storage"}}};
$.ajax
({
type: "POST",
url: "http://localhost:8080/confluence/rest/api/content/",
contentType:"application/json; charset=utf-8",
dataType: "json",
async: false,
headers: {
"Authorization": "Basic " + btoa(username+ ":" + password)
},
data: JSON.stringify(jsondata),
success: function (){
console.log('Page saved!');
},
error : function(xhr, errorText){
console.log('Error '+ xhr.responseText);
}
});
示例B
var jsondata = {"type":"page",
"title":"My Test Page",
"space":{"key":"TEST"},
"body":{"storage":{"value":"<p>This is a new page</p>","representation":"storage"}}}
$.ajax
({
type: "POST",
url: "http://localhost:8080/confluence/rest/api/content/",
contentType:"application/json; charset=utf-8",
dataType: "json",
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic YWRtaW46YWRtaW4= " );
},
data: JSON.stringify(jsondata),
success: function (){
console.log('Page saved!');
}
});
我的代码
var data = {
type: "page",
title: "New Page",
space: {
key: "TST"
},
body: {
storage: {
value: "<p>This is a new page</p>",
representation: "storage"
}
}
};
var link = 'http://confluence.mysite.com:80/rest/api/content/';
$.ajax({
url: link,
type: "POST",
dataType: "json",
crossDomain: true,
username: user.username,
password: user.password,
data: JSON.stringify(data),
contentType: "application/json",
success: function (result) {
alert('Data saved!');
},
error: function (xhr, status, error) {
alert('Status: ' + status + '\n' +
'Error: ' + error);
}
});
我尝试了以下解决方案( 上面 ),但似乎我无法通过Confluence进行身份验证。我检查了权限,我是Confluence管理组的成员。 GET命令似乎可以工作,但是在POST时,我一直在:
({"statusCode":403,"message":"You're not allowed to view that space, or it does not exist."})
我发现了类似的问题,但没有一个有可行的解决方案。大多数资源似乎是为python编写的。
是否有其他API解决方案可以证明更好?我愿意接受建议。
答案 0 :(得分:4)
再次感谢@mansilladev。在您的帮助下,我找到了解决方案。而不是使用以下方法:
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic YWRtaW46YWRtaW4= " );
}
或
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
}
使用 xhrFields 选项,用户名&amp; 密码,似乎可以执行成功的请求。
我的解决方案
$.ajax({
url: link,
type: "POST",
dataType: "json",
crossDomain: true,
username: user.username,
password: user.password,
data: JSON.stringify(data),
contentType: "application/json",
xhrFields: {
"withCredentials": true
},
success: function (result) {
alert('Data saved!');
},
error: function (xhr, status, error) {
alert(status + ' | ' + error);
}
});