Using the DNN Services Framework API with fetch

When building an SPA module in DNN (formerly Dotnetnuke), you’ll likely find yourself using the DNN WebAPI. It turns out the Javascript API for this is very XHR-centric. I wanted to use the fetch API instead.

When using fetch, instead of using beforeSend: setModuleHeaders() you’ll need to build the headers object yourself:

fetch(url, { headers: {
    "ModuleId": your-module-id-here,
    "TabId": your-tab-id-here,
}})

I modified this dotnetnuclear code to look more like this:

let service = {
    path: "PathToMyModule",
    framework: $.ServicesFramework(sbgQuestionnaireModule_Context.ModuleId),
    controller: "MyController"
}
service.baseUrl = service.framework.getServiceRoot(service.path);
// Set the headers
service.headers = {
    "ModuleId": service.framework.getModuleId(),
    "TabId": service.framework.getTabId()
};
// Set the anti-forgery token
if (service.framework.getAntiForgeryValue()) {
    service.headers["RequestVerificationToken"] = service.framework.getAntiForgeryValue();
}
service.loadUrl = service.baseUrl + "/" + service.controller + "/load";
fetch(service.loadUrl, {
    headers: service.headers
})
// etc

Thanks to Daniel Valadas for his help getting started with this.