Vue router on page refresh gets 404

血红的双手。 提交于 2020-08-10 23:00:16

问题


I am using Vue router with history mode. On button click on the current page I route it to next page. On second page when i reload i get a 404. Is there a way to handle this in Vue and redirect it to home page.

export default new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      name: "first",
      component: First
    },
    {
      path: "/abc",
      name: "abc",
      component: Second,
      props: true
    },

回答1:


you can use hash mode inested of history mode to resolve the problem on your router

let router = new Router({
    mode: "hash",
  routes: [
    {
    //and the urls with path on here ...



回答2:


This is related to how the history mode in Vue Router works. I have created a writeup about it, with a solution as well.

Depends on your server implementation you need to enable URL Rewrites there. Here's how this would be implemented using Express/Node.js:

const express = require('express');
const app = express();
const port = 80;
const buildLocation = 'dist';
app.use(express.static(`${buildLocation}`));
app.use((req, res, next) => {
  if (!req.originalUrl.includes(buildLocation)) {
    res.sendFile(`${__dirname}/${buildLocation}/index.html`);
  } else {
    next();
  }
});
app.listen(port, () => console.info(`Server running on port ${port}`));

For more info, check out https://blog.fullstacktraining.com/404-after-refreshing-the-browser-for-angular-vue-js-app/. HTH




回答3:


if any one of is facing the issue even after trying above solution, please find below method. If you have vue.config.js which has

module.exports = {
  publicPath: process.env.PUBLIC_URL || "", // <-- this is wrong
  ...
};

either remove the vue.config.js or try removing the publicPath from the exports object.

Also you can try below method if you dont want to remove the publicPath

module.exports = {
  publicPath: process.env.PUBLIC_URL || "/", // <-- this is correct now (and default)
  transpileDependencies: ["vuetify"],
};



回答4:


We have resolved this on backend, we have filter where we intercept the request and redirect it to home page. We have made it configurable.



来源:https://stackoverflow.com/questions/51630308/vue-router-on-page-refresh-gets-404

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!