Getting blank page while trying to use props in history mode in vue router

29 Views Asked by At

One of my routes in vue router requires a prop with an ID, so I added one.

const routes = [
  {
    path: '/user/:id',
    name: 'user',
    component: UserProfile,
    props: true
  },
  //...
]

While I was developing, I used WebHashHistoryMode, because it's just easier and the props are working. However for the build, I switched it to WebHistoryMode with "nicer" url:

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 }
  },
})

Then I quickly prepared an app.js file with express.js, that handle fallbacks (it's not my first vue project, and I know it works previously) for node app:

const express = require('express');
const path = require('path');
const app = express();

app.use(express.static(path.join(__dirname, 'dist')));

app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

const port = process.env.PORT || 443;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Works like a charm, but when it comes to access the /user/id page, I get only a blank page. Looks like the 'user', that comes before this /, is treated like a folder, and not like a page with prop. How can I fix it, to redirect /user/id to index.html, and of course passing the id prop?

Thanks in advance

1

There are 1 best solutions below

0
Jaku On

I found a solution, or maybe more like a workaround. I changed my declared route to "function mode", so the prop is passing with a query.

const routes = [
  {
    path: '/user',
    name: 'user',
    component: UserProfile,
    props: route => ({ id: route.query.id })
  },
  //....
]

Now the url looks like example.com/user?id=10 and not example.com/user/10. It's not the best looking url, but it will do the trick.

However if any of you know how to resolve this issue, feel free to write.