Vue Router return 404 when revisit to the url

2019-02-16 20:45发布

I just enable Vue router history mode. And it work fine when I visit to vue routing via v-href or href. But, when I try to refresh that page or go directly from browser address bar, it just return 404. Is there any option to accept refresh/revisit to that url?

The following is my Vue router configuration

var router = new VueRouter({
    hashbang: false,
    history: true,
    mode: 'html5',
    linkActiveClass: "active",
    root:  '/user'
});

5条回答
啃猪蹄的小仙女
2楼-- · 2019-02-16 21:17

Anyone else facing the same problem, I just realized that

"book/:bookId/read"  // this will not work after page reload

and this are different

"/book/:bookId/read" // this is what works even after page reload

This is of course after following what other fellas have suggested up there more importantly the catch all route in your app server side. I actually don't know why this worked, but any one with any ideas can let us know.

查看更多
forever°为你锁心
3楼-- · 2019-02-16 21:21

By refreshing the page you are making a request to the server with the current url and the server returns 404. You have to handle this on your web framework or web server level.

https://router.vuejs.org/en/essentials/history-mode.html

查看更多
\"骚年 ilove
4楼-- · 2019-02-16 21:25

I think you are missing that SPA is not server side rendering. At least for the majority. So, when you access /anything your web server won't redirect it to index.html. However, if you click on any vuejs router link, it will work due to the fact that the javascript got in action, but not the server side.

To solve this, use .htaccess and redirect all requests to index.html like so

<ifModule mod_rewrite.c>
    RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</ifModule>

Hope it helps someone!

查看更多
时光不老,我们不散
5楼-- · 2019-02-16 21:31

If someone is dealing with this issue in .NET Core as the backend of the app, a nice approach is a simple fallback handler in the Startup.cs of our .NET Core application:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
        ....Your configuration
      app.UseMvc(routes =>
      {
        routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
      });
      //handle client side routes
      app.Run(async (context) =>
      {
        context.Response.ContentType = "text/html";
        await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
      });
    }
 }

For more details: http://blog.manuelmejiajr.com/2017/10/letting-net-core-handle-client-routes.html

查看更多
劳资没心,怎么记你
6楼-- · 2019-02-16 21:43

For someone seeing this using an Express backend, there is the middleware connect-history-api-fallback that is implemented like this

const express = require('express');
const history = require('connect-history-api-fallback');

const app = express(); 
app.use(history({
  index: '/' //whatever your home/index path is default is /index.html
}));

Or with Native Node

const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

Both are suggestions in the documentation.

查看更多
登录 后发表回答