I am trying to develop an application using Laravel5.5 and Vue.js2. I am getting below error
I think vue.js can't send authentication token to Laravel. I am trying to send authentication token from vue.js is like below
Vue.http.headers.common['Authorization'] = 'Bearer ' + Vue.auth.getToken()
I placed this code in main.js file. I have a package in vue.js named Auth.js. But it is not working.
UPDATE
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'
import Auth from './packages/auth/Auth.js'
Vue.use(VueResource)
Vue.use(Auth)
Vue.http.headers.common['Authorization'] = 'Bearer ' + Vue.auth.getToken()
Vue.config.productionTip = false
router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.forVisitors)) {
if(Vue.auth.isAuthenticated()) {
next({
path: '/dashboard'
})
} else {next()}
}
else if(to.matched.some(record => record.meta.Authenti)) {
if(!Vue.auth.isAuthenticated()) {
next({
path: '/'
})
} else {next()}
} else {next()}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
Related
I want to manage cookies in the browser and use this external plugin vue-cookies. But if I call its window.$cookies.isKey(Cookies), I get an error: console.log(currentUser) = false.
Cookie exists on browser
Main.js:
import Vue from "vue"
import VueCookies from 'vue-cookies'
import App from "./App.vue"
Vue.use(VueCookies)
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
routes.js:
router.beforeEach((to, from, next) => {
const currentUser = window.$cookies.isKey(Cookies);
console.log(currentUser);
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!currentUser) {
window.location.href = "https://localhost";
} else {
next();
} {
next();
}
}
});
Any idea?
In my #vue/cli 4.0.5 app in any *.vue file I have to import axios, if I need to use it on this page, like:
<script>
import {bus} from '../../../src/main'
import appMixin from '#/appMixin'
import axios from 'axios'
...
But I expected axios to be accessible in *.vue file of my app.
In src/main.js I have defined :
import router from './router'
import store from './store'
import axios from 'axios'
...
Vue.use(axios)
moment.tz.setDefault(settingsTimeZone)
export const bus = new Vue()
axios.defaults.crossDomain = true
Vue.config.productionTip = false
Vue.prototype.$http = axios
I have this question as priorly I worked in laravel 5 / vuejs 2.6 app I have axios was accessible in all *.vue files of my app
without any definition...
Why so and if I have to write
import axios from 'axios'
in any file where I need axios ?
UPDATED BLOCK :
In my src/main.js I tried and failed as :
...
import axios from 'axios'
export const bus = new Vue()
axios.defaults.crossDomain = true
// axios.withCredentials = true
// window.axios.defaults.baseURL = window.App.baseurl;
Vue.config.productionTip = false
Vue.prototype.$http = axios
const token = localStorage.getItem('token')
if (token) {
Vue.prototype.$http.defaults.headers.common['Authorization'] = token
}
// home url in .env file
let apiUrl = process.env.VUE_APP_API_URL
alert( '++apiUrl::'+apiUrl ) // CHECK IT VALID URL
new Vue({
router,
store,
bus,
render: h => h(App)
}).$mount('#app')
Vue.use({
install (Vue) {
Vue.prototype.$api = axios.create({
baseURL: apiUrl // !!!
})
}
})
router.afterEach((to, from) => {
bus.$emit('page_changed', from, to)
})
But next in my component I commented line with axios import:
<script>
import {bus} from '../../main'
// import axios from 'axios'
import Vue from 'vue'
...
export default {
data: function () {
return {
...
}
}, // data: function () {
mounted() {
this.loadTasksData()
}, // mounted() {
methods: {
loadTasksData() {
let apiUrl = process.env.VUE_APP_API_URL
let config = {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
}
axios({url: apiUrl + '/tasks_paged/' + this.current_page, data: {}, method: 'get', config: config})
.then(response => { // Error here!
I got error :
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "ReferenceError: axios is not defined"
...
What is wrong? Did I put your construction in valid place?
Also could you please give more explanations (or provide a link) about this construction? It is about my expiarence ...
Thanks!
Try this:
Vue.use({
install (Vue) {
Vue.prototype.$api = axios.create({
baseURL: 'PUT A BASE URL IF YOU WANT'
})
}
})
So, i want to vue router.push on my store.js, but i keep getting error Cannot read property 'push' of undefined
i've tried to import vue-router in my store.js, but still in vain
here's my app.js :
import Vue from 'vue'
import VueRouter from 'vue-router'
//Import and install the VueRouter plugin with Vue.use()
Vue.use(VueRouter)
import App from './views/App'
import Home from './views/Home'
import Login from './views/Login.vue'
import Register from './views/Register.vue'
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
name: 'home',
component: Home,
meta: { requiresAuth: true }
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
},
],
});
const app = new Vue({
el: '#app',
components: { App },
router,
});
and here's my store.js :
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
accessToken: null,
loggingIn: false,
loginError: null
},
mutations: {
loginStart: state => state.loggingIn = true,
loginStop: (state, errorMessage) => {
state.loggingIn = false;
state.loginError = errorMessage;
},
updateAccessToken: (state, accessToken) => {
state.accessToken = accessToken;
},
logout: (state) => {
state.accessToken = null;
}
},
actions: {
doLogin({ commit }, loginData) {
commit('loginStart');
console.log(loginData)
axios.post('http://localhost:8000/api/login', loginData)
.then(response => {
console.log(response)
let accessToken = response.data.jwt;
document.cookie = 'jwt_access_token=' + accessToken;
commit('updateAccessToken', accessToken);
///this caused the error
this.$router.push({ path: '/' })
})
.catch(error => {
// commit('loginStop', error.response.data.error);
console.log(error)
commit('updateAccessToken', null);
console.log(error.response);
})
}
}
})
as you can see, after i call doLogin() function, and using axios, it stop at the this.$router.push({ path: '/' }) line, causing error.
You need to make a router.js file
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
...
})
export default router
In app.js replace the import of the vue-router to your new router.js and remove Vue.use(Router).
In the store, this is not the Vue instance.
Import the router.js in your store.js;
import router from './router'
Then you can access it like this;
router.push({ path: '/' })
I also noticed that you haven't add the store to the Vue instance. Import and add in app.js.
import store from './store'
...
const app = new Vue({
el: '#app',
components: { App },
router,
store //<<<<<<<<
});
hello guys i follow everything provide no google but none of these working i m new to vuex 3.0.1 and vue 2.5 below of my code
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import store from './store'
Vue.prototype.$http = axios;
var VueResource = require('vue-resource');
Vue.use(VueResource);
router.beforeEach((to, from, next) => {
console.log(this.$store.state.authUser)// this is not working
if (to.matched.some(record => record.meta.requiresAuth) &&
(!this.$store.state.authUser ||
this.$store.state.authUser === 'null')){
const authUser = localStorage.getItem('authUser')
console.log('here log');
next({ path: '/', })
}else{
console.log('bhar else redirect');
next()
}
});
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: {
App
}
})
everything work porperly if i remove this this.$store.state.authUser it work here is my store.js file
import Vue from 'vue'
import Vuex from 'vuex'
import userStore from './user/userStore.js'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
modules:{
userStore
},
strict:debug
})
here is my userStore
const state = {
authUser:null
}
const mutations = {
SET_AUTH_USER(state,userObj){
state.authUser = userObj
}
}
const actions = {
setUserObject :({commit},userObj) =>{
commit('SET_AUTH_USER',userObj)
}
}
export default {
state, mutations, actions
}
here is my login succcess from where i trie to dispatch value in store note i have value in store
this.$store.dispatch('setUserObject',response.data.id)
i does everything properly but don't know why it throw error Cannot read property 'state' of undefined
You are accessing your store in the router's beforeEach guard using this.$store. But this is not your vue instance and has no $store property.
Since you are importing the store using import store from './store', you can use that store import to access your store as follows:
router.beforeEach((to, from, next) => {
console.log(store.state.userStore.authUser)// this will log put authUser from userStore module
if (to.matched.some(record => record.meta.requiresAuth) &&
(!store.state.userStore.authUser ||
store.state.userStore.authUser === 'null')){
const authUser = localStorage.getItem('authUser')
console.log('here log');
next({ path: '/', })
}else{
console.log('bhar else redirect');
next()
}
});
The authUser property belongs to the userStore module, so to access it you use
store.state.userStore.authUser
I'm getting the following error when trying to implement vue-router.
Unknown custom element: <router-view> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
Where do I need to provide the name option?
A lot of the tutorials I'm looking at seem to be an older version of vue-router. I follow the set-up process but can't get it to work.
Might there be something special I have to do when using the webpack cli template?
I'm also using the vue-router cdn.
Here's my main.js
import Vue from 'vue'
import App from './App'
import ResourceInfo from '../src/components/ResourceInfo'
var db = firebase.database();
var auth = firebase.auth();
const routes = [
{ path: '/', component: App },
{ path: '/info', component: ResourceInfo }
]
const router = new VueRouter({
routes
})
/* eslint-disable no-new */
var vm = new Vue({
el: '#app',
components: { App },
created: function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// Get info for currently signed in user.
console.log(user);
vm.currentUser = user;
console.log(vm.currentUser);
} else {
// No user is signed in.
}
})
// Import firebase data
var quizzesRef = db.ref('quizzes');
quizzesRef.on('value', function(snapshot) {
vm.quizzes = snapshot.val();
console.log(vm.quizzes);
})
var resourcesRef = db.ref('resources');
resourcesRef.on('value', function(snapshot) {
vm.resources.push(snapshot.val());
console.log(vm.resources);
})
var usersRef = db.ref('users');
usersRef.on('value', function(snapshot) {
vm.users = snapshot.val();
console.log(vm.users);
})
},
firebase: {
quizzes: {
source: db.ref('quizzes'),
asObject: true
},
users: {
source: db.ref('users'),
asObject: true
},
resources: db.ref('resources')
},
data: function() {
return {
users: {},
currentUser: {},
quizzes: {},
resources: []
}
},
router,
render: h => h(App)
})
And my App.vue
<template>
<div id="app">
<navbar></navbar>
<resource-info :current-user="currentUser"></resource-info>
<router-view></router-view>
</div>
</template>
<script>
import Navbar from './components/Navbar'
import ResourceInfo from './components/ResourceInfo'
export default {
name: 'app',
props: ['current-user'],
components: {
Navbar,
ResourceInfo
}
}
</script>
<style>
</style>
In your main.js file, you need to import VueRouter as follows:
import Vue from "vue" // you are doing this already
import VueRouter from "vue-router" // this needs to be done
And below that, you need to initialize the router module as follows:
// Initialize router module
Vue.use(VueRouter)
Other than the above, I cannot find anything else missing in your code, it seems fine to me.
Please refer to the installation page in docs, under NPM section:
http://router.vuejs.org/en/installation.html
First install vue router by using "npm install vue-route" and follow the bellow in main.js
import Vue from 'vue'
import Router from 'vue-router'
import App from './App'
import ResourceInfo from '../src/components/ResourceInfo'
var db = firebase.database();
var auth = firebase.auth();
Vue.use(Router)
var router = new Router({
hashbang: false,
history: true,
linkActiveClass: 'active',
mode: 'html5'
})
router.map({
'/': {
name: 'app',
component: App
},
'/info': {
name: 'resourceInfo',
component: ResourceInfo
}
})
// If no route is matched redirect home
router.redirect({
'*': '/'
});
// Start up our app
router.start(App, '#app')
This might be solve your problem
You forgot to import vue-router and initialize VueRouter in main.js
import VueRouter from "vue-router"
Vue.use(VueRouter)