javascriptundefinedsession-cookiesdurandalbearer-token

"setCookies" function not defined in Durandal single page app


I am currently working on a single page app using Durandal.

I have two functions, one of which is used to 'save' a Bearer token after login in order to later make API calls, and the others purpose being to retrieve said Bearer token when called from different pages in the app (to make calls).

I have created two additional functions, which are used to set cookies and retrieve cookies. 'setCookies' is to run simultaneously with 'setToken', while 'getCookies' is to run simultaneously with 'getToken'.

The problem I am having with this is that my browser is returning 'Uncaught ReferenceError: setCookies is not defined'.

Does anybody know what I am doing wrong? Code below:

define(['durandal/app', 'knockout'], function (app, ko) {
return {
    bearerToken: ko.observable(),
    getToken: function () {
        this.bearerToken(getcookies());
        return this.bearerToken();
    },
    setToken: function (token) {
        setCookies("Bearer", token);
        this.bearerToken(token);
        console.error(this.bearerToken());
    },
    getCookies: function (cookieName) {
        var v = document.cookie.match('(^|;) ?' + cookieName + '=([^;]*)(;|$)');
        return v ? v[2] : null;
    },
    setCookies: function (cookieName, cookieValue) {
        document.cookie = cookieName + "=" + cookieValue;
    }
};
});

Solution

  • You have to use this.setCookies(), not just setCookies(). This is because the function is present inside the same object that you are returning.

    Here this refers to the current object. In your code, you have used this.bearerToken. You have to call setCookies() function in the same way.

    Change the method like this

    setToken: function (token) {
        this.setCookies("Bearer", token);
        this.bearerToken(token);
        console.error(this.bearerToken());
    },