Vue 3 - How to disable adding trailing slash? - vue.js

Problem statement : Vue app changes the URL after loading the scripts and adds a slash to the end. This only happens for routes where the path matches /.
I have the server configured like this :
/game(.*) => Vue 3 App
anything else => reverse proxy
My router :
const routes = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue'),
},
{
path: '/:pathMatch(.*)',
component: () => import('../views/NotFound.vue'),
},
];
const router = createRouter({
history: createWebHistory('/game/'),
routes,
strict: true
});
What's happening :
If I request http://localhost/game, the URL in the address bar changes to http://localhost/game/. I don't understand why this is happening. What I know for sure is that it's Vue that does it, not the server.
Screen :
If I add something else to the URL, for example http://localhost/game/notfound, then the slash will not be added to the end.
UPD
Additionally, I show my config.vue.js :
process.env.VUE_APP_VERSION = require('./package.json').version;
module.exports = {
publicPath: (process.env.NODE_ENV === 'production' ? '/game' : '/'),
devServer: {
proxy: {
'^/api': {
target: 'http://app:'+process.env.APP_PORT,
ws: false,
changeOrigin: true
},
}
},
lintOnSave: 'default',
productionSourceMap: false
};
And content console.log(process.env) :
{
"NODE_ENV": "production",
"VUE_APP_ENV": "dev",
"VUE_APP_VERSION": "1.0.0",
"BASE_URL": "/game/"
}

Related

the redirect url contains the absolute and relative path while redirection from route.beforeach

In my vue js application, I have a vue-router setup as follows: In route.beforeach I am checking whether the application is already authenticated or not, base upon that I had to redirect to login page.
let router = new VueRouter({
routes: routes,
mode: "history",
scrollBehavior: () => ({ x: 0, y: 0 }),
});
Vue.use(VueGtag, {
config: { id: process.env.VUE_GTAG }
}, router);
export default router;
router.beforeEach((to, from, next) =>
{
if (to.matched.some(record => record.meta.requiresAuth) && !(authService.myMsal.getAllAccounts().length > 0))
{
next({
name: "page-login",
query: {
redirect: to.fullPath
}
});
} else
{
next()
}
});
and in route.js it is setup as:
const routes = [
{
path: '/login',
name: 'page-login',
component: Login
},
{
path: '/',
component: () => import('layouts/MyLayout.vue'),
meta: {
requiresAuth: true,
},
children: [
{
name: 'home',
path: '',
component: () => import('components/Home.vue'),
meta: {
requiresAuth: true,
},
},
],
},
]
In router.beforeEach when the application has to redirect to page-login, it is redirected with a full path as: http://localhost:8080/http:/localhost:8080/login?redirect=%2F
it should have to be redirected to http:/localhost:8080/login, what is causing this behavior?

VueJs route paths in production

I have a VueJs app that is hosted on a subdomain on my server.
I am able to access the base route without problem like so: http://dev.myserver.com/app-basename
However in my routes file I have a route to eg. /fb/:ref. But going to this (http://mdev.myserver.com/app-basename/fb/start) route is returning a 404 page instead.
Here is a piece of my route file:
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
return { x: 0, y: 0 }
},
routes: [
{
path: '/',
name: 'get-started',
component: () => import('#/views/GetStarted.vue'),
meta: {
layout: 'full',
},
},
{
path: '/fb/:ref',
name: 'fb-get-started',
component: () => import('#/views/GetStarted.vue'),
meta: {
layout: 'full',
},
}
]
})
I added a .htaccess folder to the app-basename folder with FallbackResource /index.html but that also didn't work.
Anyone knows what I can do to fix this?

Vue How to fix 404 error when using nuxt proxy and nuxt axios

In my vue-app I'm using the #nuxtjs/proxy together with #nuxtjs/axios but for some reason I don't know, I always get an Request failed with status code 404 -error when calling the api.
Here is my nuxt.config.js
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true,
},
proxy: {
"/api": {
target: "https://url-to-api.com/api",
pathRewrite: { "^/api/": "" },
}
},
then in my vue-component
created(){
const { data } = await this.$axios.get(
`/api/products/all`
)
...
}
when I check on the network tab, the request is:
https://mypage.com/api/products/all
that request returns like mentioned above Request failed with status code 404
What am I doing wrong?
nuxt version: 2.15.8
Try this:
// nuxt.config.js
axios: {
baseURL: '/',
browserBaseURL: '/',
proxy: true,
},
proxy: {
'/api/': {
target: process.env.BASE_URL,
pathRewrite: {'^/api/': ''},
},
},
publicRuntimeConfig: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL,
},
},
privateRuntimeConfig: {
axios: {
baseURL: process.env.BASE_URL,
},
},
and in your component:
created(){
const { data } = await this.$axios.get(
`products/all`
);
}
in .env:
BROWSER_BASE_URL=/api/
BASE_URL=https://url-to-api.com/api/
it works for me.

Vue router fails after build

I developed an application in vue 3.10.0 with a template downloaded from Vue official website. Works well when run with npm run serve but after build, browser window is blank. Build is successful and no errors in console
I have changed the public path in the vue config file to where it's been loaded on the server.
The config file looks like this:
const webpack = require('webpack');
const isProd = process.env.NODE_ENV === "production";
module.exports = {
publicPath: isProd ? "/facil-users/" : "",
//publicPath: isProd ? "" : "",
configureWebpack: {
// Set up all the aliases we use in our app.
plugins: [
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 6
})
]
},
pwa: {
name: 'Facil app',
themeColor: '#172b4d',
msTileColor: '#172b4d',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: '#172b4d'
},
css: {
// Enable CSS source maps.
sourceMap: process.env.NODE_ENV !== 'production'
}
};
Route file looks like this:
const routes = [{
path: '/',
redirect: 'dashboard',
component: DashboardLayout,
children: [{
path: '/dashboard',
name: 'dashboard',
component: () => import('./views/Dashboard.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/user',
name: 'single user',
component: () => import('./views/users/ViewSingleUser.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/users',
name: 'users',
component: () => import('./views/users/ViewUsers.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/profile',
name: 'profile',
component: () => import('./views/users/UserProfile.vue'),
meta: {
requiresAuth: true
}
},
{
path: '/register-user',
name: 'regiseter user',
component: () => import('./views/authentication/NewRegistration.vue'),
meta: {
//isAdmin: true,
requiresAuth: true
}
},
]
},
]
const router = new VueRouter({
mode: 'history',
routes: routes
});
I ought to have the view responding just like i have it when i do an npm run serve. Access from localhost/facil-users/ returns a black screen, i have also added the .htaccess code as suggested on the vue official website.
Thanks in advance.

Router part of PWA opens blank on device (with Vue)

I built 2 PWA based on Vue (with Vue UI templates, with router and PWA already set up) but I get on both the same issue: after I add to Homescreen on device, when I open it from the app icon, the router viez doesn't show up and stays blank until I click on a router link. I don't understand why.
Example of one of them, my portfolio:
URL Link
GitHub Link
Some parts of files here that I think related to the issue:
router.js:
export default new Router({
mode: 'history',
base: 'index.html',
routes: [
{
path: '/',
name: 'home',
component: Home
}
]
})
firebase.json:
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
Edit:
Checkout #webmint answer below, probably solve problem im better and clean way.
Orginal Post:
I solved my problem adding an alias to start page in routes (in my case "Login")
in manifest.json:
{
...
"start_url": "index.html",
...
}
in router config:
let router = new Router({
...
routes: [
{ path: '/index.html',
component: Login,
alias: '/'
},
{
path: '/',
name: 'login',
component: Login
},
...
Had same issue. Turns out that solution is quite simple. You have to add/change this in manifest.json
"start_url": "/",
"scope": "/"
At the risk of repeating kaligari's answer, I'd say that the required part is only
{ path: '/index.html', component: Home }
in the router config. You can also use an alias to make it look better on the client. Although, when used as a PWA, this makes no difference since the address bar is not visible.
{ path: '/index.html', component: Home, alias: '/' }
Add the following to your vue.config.js:
pwa: {
workboxOptions: {
navigateFallback: '/index.html',
},
},
If it can help someone, here is what worked for me (after trying a lot of the above solutions and other ones on the web...) :
Context: PWA with Vue.js CLI 3.
Problem: After installing the URL on the "desktop" through the "Add to home screen" option in Safari, clicking on the icon opened a white page.
The same on Android (Chrome) was working perfectly.
I solved it with the following config:
manifest.json
...
"start_url": "/index.html",
...
router.json (includes some Firebase config elements)
//......
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
redirect: {
path: '/projects'
}
},
{
path: '/login',
name: 'Login',
component: Login,
},
{
path: '/projects',
name: 'Projects',
component: Projects,
meta: {
requiresAuth: true
}
},
//......
]
});
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(x => x.meta.requiresAuth);
const currentUser = firebase.auth().currentUser;
if (requiresAuth && !currentUser) {
next('/login');
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});
export default router;
vue.config.js
module.exports = {
pwa: {
name: 'Xxxxxxxxxx',
themeColor: '#000000',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
workboxOptions: {
navigateFallback: '/index.html',
},
}
};