我正在努力将项目添加到Apache Cordova应用程序的sharepoint列表中。它首先提示用户登录然后它将发送HTTP Post以进行数据输入。
我有以下代码:
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(FormatAndUpload(authResult, data), errorCallback);
}
function FormatAndUpload(authResponse, data) {
var token = authResponse.accessToken;
var expiry = authResponse.expiresOn;
console.log("Token acquired: " + authResponse.accessToken);
console.log("Token will expire on: " + authResponse.expiresOn);
$.ajax({
url: "https://my.sharepoint.com/_api/web/lists/getbytitle('" + Test + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"Authoriztion":"Bearer " + token
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
我遇到的问题是在acquireTokenAsync完成之前调用了FormatAndUpload方法,因此传递给FormatAndUpload方法的authResponse变量为null。
我对Javascript / JQuery中的promise框架不太熟悉,但我的印象是该事件只应在完成上一个方法时触发。
在尝试POST之前,有没有人知道如何正确等待登录完成?
答案 0 :(得分:1)
你做了什么FormatAndUpload(authResult,data);是错误的,传递回调的正确方法是
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
所以你的saveToSharepoint将是这样的
function saveToSharepoint(data) {
var authority = "https://login.microsoftonline.com/common/";
var authContext = new Microsoft.ADAL.AuthenticationContext(authority);
var authResult = authContext.acquireTokenAsync("https://my.sharepoint.com", "4be098f8-2184-4831-9ef7-3d17dbbef6a0", "http://localhost:4400/services/office365/redirectTarget.html")
.then(function(authResult){
FormatAndUpload(authResult, data);
}, errorCallback);
}
答案 1 :(得分:0)
感谢Newbee Dev的回答,你说得对,因为我没有正确地制定那个方法。
对于其他任何关于SharePoint的人,我实际上重新格式化了代码,使其按预期工作,因此saveToSharepoint方法如下所示:
function saveToSharepoint(data) {
var AuthenticationContext = Microsoft.ADAL.AuthenticationContext;
AuthenticationContext.createAsync("https://login.microsoftonline.com/common/")
.then(function (authContext) {
authContext.acquireTokenAsync(
"https://my.sharepoint.com", // Resource URI
"4be098f8-2184-4831-9ef7-3d17dbbef6a0", // Client ID
"http://localhost:4400/services/office365/redirectTarget.html" // Redirect URI
).then(function (authResult) {
FormatAndUpload(authResult, data);
}, function (err) {
console.log(err);
});
}, function (err) {
console.log(err);
});
}
要注意的主要是异步创建AuthenticationContext,这样,整个登录过程完成后,FormatAndUpload调用。我以为我会把这个发布给其他看到这个关于Sharepoint并被卡住的人。