![](/img/trans.png)
[英]How to call an external restful using $.ajax from within a SharePoint-hosted app (SharePoint Online)
[英]POST httpRequest/AJAX to external API in Sharepoint Online
風景
我試圖致電IBM Cloud中的服務,並且已經發送了文件。 此請求必須使用JavaScript在Sharepoint Online中完成。 在請求中將發送文件。 問題
我在Sharepoint Online中遇到跨域(Sharepoint端)和錯誤請求(IBM端)的問題。 我嘗試過秘密方式。
嘗試次數
解決跨域問題:
$.ajax({
url: "../_api/SP.WebProxy.invoke",
type: "POST",
data: JSON.stringify(
{
"requestInfo": {
"__metadata": { "type": "SP.WebRequestInfo" },
"Url": "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={API-KEY}&version=2016-05-20",
"Method": "POST",
"Headers": {
"results": [{
"__metadata": { "type": "SP.KeyValue" },
"Key": "Accept",
"Value": "application/json;odata=verbose",
"ValueType": "Edm.String"
}, {
"__metadata": { "type": "SP.KeyValue" },
"Key": "Content-Type",
"Value": "application/json",
"ValueType": "Edm.String"
}]
}
,
"Body": JSON.stringify({ "files":[ { "name":"imagem.png","content": image } ]})//Problem here
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert("Sucesso");
console.log(data.d.Invoke.StatusCode);
console.log(JSON.stringify(data.d.Invoke.Body));
},
error: function (data) {
alert("Falha");
console.log(arguments[2]);
}
});
這樣就解決了跨域(Sharepoint)問題,但是我收到了錯誤的請求(IBM API)。 模型請求發送文件顯示如下。
"Body": JSON.stringify({ "files":[ { "name":"imagem.png","content": image } ]})
解決錯誤的請求問題:
function CORS() {
var data = new FormData();
data.append("imagemTeste", $("#imagem")[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key={API-KEY}&version=2016-05-20');
xhr.onload = function (e) {
var data = JSON.parse(this.response);
console.log(data);
}
xhr.send(data);
}
在這里,解決了錯誤請求(IBM API)的問題,但是出現了跨域錯誤(Sharepoint)。
我沒有辦法解決這個問題。
一種選擇是從服務器調用API。 例如,您可以使用Cloud Functions調用此API。 任何其他服務器端環境都應該起作用。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.