There are two utility JavaScript libraries you reference in this HTML page:
- common/csrf.js
for the handling of CSRF tokens
- common/error.js
for producing error messages
Create a common
folder in resources and add these two files.
Here is the coding of csrf.js
:
/*eslint no-console: 0, no-unused-vars: 0, no-use-before-define: 0, no-redeclare: 0*/
$.ajaxSetup({
beforeSend: function(xhr,settings) {
if (settings && settings.hasOwnProperty("type")
&& settings.type !== "GET"){
var token = getCSRFToken();
xhr.setRequestHeader("X-CSRF-Token", token);
}
},
complete: function(xhr,textStatus) {
var loginPage = xhr.getResponseHeader("x-sap-login-page");
if (loginPage) {
location.href = loginPage + "?x-sap-origin-location=" + encodeURIComponent(window.location.pathname);
}
}
});
function getCSRFToken() {
var token = null;
$.ajax({
url: "/xsjs/csrf.xsjs",
type: "GET",
async: false,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
complete: function(xhr) {
token = xhr.getResponseHeader("X-CSRF-Token");
}
});
return token;
}
And here is the code for error.js
:
/*eslint no-console: 0, no-unused-vars: 0, no-use-before-define: 0, no-redeclare: 0*/
function onErrorCall(jqXHR, textStatus, errorThrown) {
var page = sap.ui.getCore().byId("pageID");
page.setBusy(false);
if (typeof jqXHR.status === "undefined") {
var errorRes = JSON.parse(jqXHR.response.body);
sap.m.MessageBox.show(
errorRes.error.innererror.errordetail.DETAIL, {
icon: sap.m.MessageBox.Icon.ERROR,
title: "Service Call Error",
actions: [sap.m.MessageBox.Action.OK],
styleClass: "sapUiSizeCompact"
});
} else {
if (jqXHR.status === 500 || jqXHR.status === 400) {
sap.m.MessageBox.show(jqXHR.responseText, {
icon: sap.m.MessageBox.Icon.ERROR,
title: "Service Call Error",
actions: [sap.m.MessageBox.Action.OK],
styleClass: "sapUiSizeCompact"
});
return;
} else {
sap.m.MessageBox.show(jqXHR.statusText, {
icon: sap.m.MessageBox.Icon.ERROR,
title: "Service Call Error",
actions: [sap.m.MessageBox.Action.OK],
styleClass: "sapUiSizeCompact"
});
return;
}
}
}
function oDataFailed(oControlEvent) {
sap.m.MessageBox.show("Bad Entity Definition", {
icon: sap.m.MessageBox.Icon.ERROR,
title: "OData Service Call Error",
actions: [sap.m.MessageBox.Action.OK],
styleClass: "sapUiSizeCompact"
});
return;
}