问题
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'
});
回答1:
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
回答2:
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!
回答3:
If you don't really care about the hash in the url, you can just set the mode to hash in you router configuration file: mode: 'hash'
That works fine without the need to setting up the server side.
const router = new VueRouter({
routes: Routes,
mode: 'hash'
});
Hash mode comes by default in vue, so it should work even if you leave blank instead of mode: 'hash'
.
回答4:
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
回答5:
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.
回答6:
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.
回答7:
I'm using Razor Pages with .net core 2.2 and I got this working:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
routes.MapRoute(
name: "spa-fallback",
template: "{*url:regex(^((?!.css|.map|.js|sockjs).)*$)}",
defaults: new { controller = "Index", action = "Index" });
});
回答8:
For Netlify, add the following to a public/_redirects
file...
/* /index.html 200
See https://www.netlify.com/docs/redirects/#history-pushstate-and-single-page-apps
来源:https://stackoverflow.com/questions/36399319/vue-router-return-404-when-revisit-to-the-url