5

I am using vuejs 2 with laravel 5.4 which is integrated in it.. I am trying to build an authentication service that uses laravel passport. I have been able to log in user but the problem is with vue js. I have created a custom Auth package to handle front end token. I am getting an error of Cannot read property 'setToken' of undefined

my auth package is this :

export default function (Vue){
Vue.auth = {
    // set token 
    setToken : (token , expires_in) =>{
    localStorage.setItem('token' , token);
    localStorage.setItem('expires_in' , expires_in)
    },
    // get token
    getToken : ()=>{

    },

    // destroy token


    // isAuthenticated
    isAuthenticated : ()=>{
    if(this.getToken())
    {
        return true
    }
    return false
    }
}
Object.defineProperties(Vue.prototype , {
    $auth : {
        get: ()=>{
        return Vue.auth
    }
    }
})
}

And this is my bootstrap file :

       window._ = require('lodash');

    /**
     * We'll load jQuery and the Bootstrap jQuery plugin which provides support
     * for JavaScript based Bootstrap features such as modals and tabs. This
     * code may be modified to fit the specific needs of your application.
     */
      window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');

/**
 * Vue is a modern JavaScript library for building interactive web interfaces
 * using reactive data binding and reusable components. Vue's API is clean
 * and simple, leaving you to focus on building your next great project.
 */

window.Vue = require('vue');

import VueRouter from 'vue-router';

import Auth from './packages/auth/Auth.js';

Vue.use(VueRouter);
Vue.use(Auth);

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

axios.defaults.baseURL = 'http://localhost/iAttendanceLaravel/public/';



/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: 'your-pusher-key'
// });

And this is finally my login method in login.vue file :

  methods: {
        login: function () {

            var data = {
                client_id : 2,
                client_secret : '8WCDtW3wKeeNUBgwHviFoX7JmaVPU0HjFto9kwqv',
                grant_type     : 'password',
                username : this.loginForm.email,
                password : this.loginForm.password
            };

            axios.post('/oauth/token', data)
                .then(function (response) {
                    console.log(response);
                    self.$auth.setToken(response.body.access_token , response.body.expires_id + Date.now());
                })
                .catch(function (error) {
                    console.log(error);
                });

        },
6
  • Modules need to expose install method, like this: stackoverflow.com/a/43193455/7636961 Also, you export a function which accepts param Vue, but you don't call this function afterwards. Try to export a constant or call o function, and add install method to your plugin. Commented Apr 20, 2017 at 7:34
  • tried with install method too. still doesnt work. Commented Apr 20, 2017 at 7:42
  • what do you mean by this ** Also, you export a function which accepts param Vue, but you don't call this function afterwards. ** Commented Apr 20, 2017 at 7:43
  • I posted an answer with example. Using const instead of function. Commented Apr 20, 2017 at 8:10
  • yes i know i have marked that right Commented Apr 20, 2017 at 9:23

2 Answers 2

1

The working code: https://jsfiddle.net/wostex/63t082p2/30/ (minimal functionality, just to show how it works)

const auth = {
    setToken : () => {
      console.log('inside setToken');
    },
    install: function(Vue){
      Object.defineProperty(Vue.prototype, '$auth', {
        get () { return auth }
      })
    }
};

Vue.use(auth);

new Vue({
    el: '#app',
    mounted() {
      this.$auth.setToken();
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

can you explain how can i use it from another file
I edited answer to handle this issue. You have to pass Vue to install function in this case.
0

i can't find where is definition of self . you can replace 'self.$auth' with this.$auth and you should use arrow-function instead of callback of then()

3 Comments

Do you use arrow-function instead of callback of then()?
why would that matter ? then is getting response. I tried . still same error
In arrow-function,this is pointed to parent scope. if you use arrow-function ,this will be pointed to Vue.prototype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.