cannot use vue-router routes in axios file - vue.js

I need to redirect to login page if backend throws 401-Unauthorised error. But when I try to use router.push('/login) it throws router is not defined error in axios interceptor.
Here is my axios.js file.
import Vue from 'vue'
import axios from "axios"
import router from '../router'
_axios.interceptors.response.use(
function(response) {
return response
},
function(error) {
if(error.response.status == 401){
router.push('/login')
}
return Promise.reject(error)
}
)
This is router.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'Login',
meta: {
layout: 'login',
requireAuth: false,
icon: null
},
component: () => import(/* webpackChunkName: "login" */
'../components/common/auth/login-form'),
}]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
And defining {router} in axios gives this error in terminal npm run serve:
If I try with import router from '../router' in axios file I got this error:

use default export import router from '../router' instead of named import like you have in answer, `cause you have default export only in file where you define router

Related

Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=535663ae' does not provide an export named 'default'

I'm using a js framework known as griptape(used for blockchain). I'm getting this error when trying to use the vue router.
import Vue from "vue"; //Error **does not provide an export named 'default'**
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/about",
name: "About",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue"),
},
];
const router = new VueRouter({
routes,
});
export default router;
while my vue.d.ts file looks like this
import { CompilerOptions } from '#vue/compiler-dom';
import { RenderFunction } from '#vue/runtime-dom';
export declare function compile(template: string | HTMLElement, options?: CompilerOptions): RenderFunction;
export * from "#vue/runtime-dom";
export { }
router.d.ts file look like this
I think you are using Vue 3. You should check your vue-router version. If you just run npm i vue-router now, the version should be "^3.5.3". Try to use npm i vue-router#next to install newer version.
Then export router like this:
import {createRouter, createWebHistory} from 'vue-router'
const routes = [
{
path:'/',
name:"Home",
component:()=>import('./pages/Home.vue')
}
,
{
path:'/about',
name:"About",
component:()=>import('./pages/About.vue')
}
]
const router = createRouter({
history:createWebHistory(),
routes
})
export default router
You technically didn't ask a question I will try to explain the error. Your error states what you try to do, importing a default export from the module 'vue' which doesn't exist.
// some ts file
import Vue from "vue";
// the module
export default {}
If there should be a named export called 'Vue' you should write it as follows: import { Vue } from 'vue'
references:
https://www.typescriptlang.org/docs/handbook/modules.html#default-exports

Vue.js App not compiling after adding Vuex

I have been working on a web app and decided I needed to implement Vuex to help. I tried implementing it and messed up at first, but I don’t know what’s causing it now. I may be overlooking something but I just can’t find it, any help?
Router (index.js)
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Products from '../views/Products.vue'
import ProductListView from '../components/ProductListView.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path:'/products',
name: 'Products',
component: Products,
children: [
{
path: ':ptype',
name: 'ProductListView',
component: ProductListView,
props: true
}
]
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
Store (store.js)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
}
})
export default store
App (main.js)
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from 'store.js'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
I'm getting this error when I try running yarn serve in PowerShell
yarn run v1.22.4
$ vue-cli-service serve
'vue-cli-service' is not recognized as an internal or external command,
operable program or batch file.
error Command failed with exit code 1.

Vue.js using POST error(Sysntax but not find out)

Thank you for reading this question.
I got a syntax error, but I can't find where.
I am using Vue.js & bootstrap, I am working on shopping cart functionality. In order for endpoints to work you need to pass a special authentication header:
Authorization: kazuhisa.noguchi.ghsd75#gmail.com
import Vue from 'vue'
import App from './App.vue'
import BootstrapVue from 'bootstrap-vue'
import VueRouter from 'vue-router'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import MainPage from './components/MainPage.vue'
import HelpPage from './components/HelpPage.vue'
import ProductPage from './components/ProductPage.vue'
import CategoryPage from './components/CategoryPage.vue'
Vue.config.productionTip = false
Vue.use(BootstrapVue)
Vue.use(VueRouter)
const router = new VueRouter({
routes: [{
path: '/',
component: MainPage
},
{
path: '/help',
component: HelpPage
},
{
path: '/products/:productId',
component: ProductPage
},
{
path: '/categories/:categoryAlias',
component: CategoryPage
}
],
mode: 'history'
})
axios.defaults.headers.common['Authorization'] = 'azuhisa.noguchi.ghsd75#gmail.com';
axios.post("https://euas.person.ee/user/carts/").then(
response => {
new Vue({
render: h => h(App),
router: router,
data: {
cart: response.data,
saveCard() {
axios.put("https://euas.person.ee/user/carts/" +
this.cart.id, this.cart)
}
}
}).$mount('#app')
}
};
All my best,

Importing Vue Router inside a JavaScript file causes 'Module Parse Failed' Error

I am trying to access the router in the interceptor of axios, but when I import the file in a .js Axios file, an error Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > <template> occurs.
Here is a sample of the router.js file:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: "/settings",
name: "settings",
component: require('#/views/Settings.vue'),
}
]
};
export default new Router(router);
And the interceptor file contains:
import router from './router';
Why do you using require('#/views/Settings.vue')?
Instead try to use import function.
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
const router = {
base: process.env.BASE_URL,
routes: [
{
path: '/settings',
name: 'settings',
component: () => import('#/views/Settings.vue'),
},
],
};
export default new Router(router);
PS: Answer your comment.
In main.js file export the instance variable:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
let vm = new Vue({
router,
render: h => h(App),
}).$mount('#app');
export default vm; // ATENTION HERE
In axios.js file import the main.js and access the $router:
import vm from './main.js';
...
// YOUR INTERCEPTOR
vm.$router.push({ name: 'settings' });
...

vue-router not pushing while inside a store

This is my store
import Vue from 'vue'
import Vuex from 'vuex'
import router from '#/main';
import mainStore from './modules/main-store';
import loginStore from './modules/login-store';
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
mainStore,
loginStore
}
});
and my login-store.js
//other imports
import router from '#/main';
const actions = {
forceLogout(){
localStorage.removeItem('token')
localStorage.removeItem('user')
delete API.defaults.headers.common['Authorization']
router.push('/login')
},
//other actions
}
And my router.js:
import store from './stores'
Vue.use(Router)
const router = new Router({
mode: 'hash',
routes: [
{
path: '/login',
name: 'login',
component: Login,
},
]
//other routes
})
//... some router.afterEach and router.beforeEach
export default router
There is a case where I need the store to force a logout and this is how I do it, I call the forceLogout action from a file named api.js
import store from './../stores';
//....
if(error_msg == 'Not_Logged'){
store.dispatch('forceLogout')
}
//....
I've tried changing an import:
import router from 'vue-router'
//...
router.push('/login')
Same thing with importing
import router from '#/main'
router.push('/login')
and I keep on getting TypeError: Cannot read property 'push' of undefined
I don't see where you're exporting your router.
router.js should include export default router so then when you import router from '#/main' it actually imports something.