我正在尝试通过SAPUI5应用程序中的AJAX调用访问SAP Successfactors API。
我可以使用POSTMAN并提供基本身份验证凭据来正常访问API。
如何直接在AJAX中提供这些凭据。我从众多帖子中尝试了多种方法,但似乎没有任何方法可以工作。
来自Google Dev Tools的响应(“控制台”选项卡)
Failed to load https://api2.successfactors.eu/odata/v2/PerPerson?$select=personId: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://webidetesting#####-#####.dispatcher.hana.ondemand.com' is therefore not allowed access.
来自Google Dev Tools的响应(“网络”标签)
Authentication credentials are required. Please provide a valid username, password and company id
Ajax。
var aData = jQuery.ajax({
type: "GET",
contentType: "application/json",
crossDomain: true,
url: "https://api2.successfactors.eu/odata/v2/PerPerson?$select=personId",
xhrFields: {
withCredentials: true
},
beforeSend: function (req) {
req.setRequestHeader('Authorization', 'Basic ' + btoa('Username:Password'));
req.setRequestHeader('Access-Control-Allow-Origin', '*');
},
headers: {
"Authorization": "Basic " + btoa("Username" + ":" + "Password"),
"Access-Control-Allow-Origin": "*"
},
username: "Username",
password: "Password",
dataType: "json",
async: false,
success: function (data, textStatus, jqXHR) {
oModel.setData({
modelData: data
});
alert("success to post");
},
error: function (oError) {
console.log(oError);
}
});
答案 0 :(得分:1)
可能是以下问题:
1)发送之前的用户名是否为USERNAME @ COMPANY:PASSWORD?
2)端点URL应该根据您的数据中心,也许DC2是正确的,但也可能是DC12? https:// api12 .successfactors.eu / odata / v2 / PerPerson?$ select = personId代替https:// api2 .successfactors.eu / odata / v2 / PerPerson?$ select = personId
3)传递对您的成功功能的引用
var that = this;
....
success: function (data, textStatus, jqXHR) {
var oModel = that.getView().getModel(); // get your model, instatiated outside this method
oModel.setData({
modelData: data
});
alert("success to post");
},
error: function (oError) {
console.log(oError);
}
....
4)使用SAP Cloud Platform以避免跨域问题的正确方法!
SAP CP中的目的地(连接性->目的地):
别忘了检查连接并收到HTTP状态代码= 200!
Name: sap_hcmcloud_core_odata,
Type: HTTP
URL: https://api12preview.sapsf.eu
Auth: Internet, Basic Authentication
Your User (Username@Company),
Your Password
Properties
WebIDEEnabled = true
WebIDESystem = SFSF
WebIDEUsage = odata_gen
neo-app.json 添加路由:
{ "path": "/sf-dest",
"target": {
"type": "destination",
"name": "sap_hcmcloud_core_odata"
},
"description": "SFSF Connection"
}
在您的控制器
中sap.ui.define([
"sap/ui/core/mvc/Controller"], function (Controller) {
"use strict";
return Controller.extend("yourNamespace.yourAppName.controller.Main", {
onInit: function () {
var oModel = new sap.ui.model.json.JSONModel();
var sHeaders = {
"Content-Type": "application/json",
"Accept": "application/json",
};
//sending request
oModel.loadData("/sf-dest/odata/v2/PerPerson?$select=personId", null, true, "GET", null, false, sHeaders);
console.log(oModel);
}
});
});
答案 1 :(得分:0)
在这种情况下,SCP Destination是答案,但是如果有2个调用,一个调用身份验证API(以检索令牌),另一个调用GET API(将检索到的令牌用作身份验证?)
答案 2 :(得分:0)
答案很简单,就是创建一个没有身份验证的目的地并在AJAX中应用所有授权