解决Vue history模式下路由跳转时页面404问题
发布日期:2021-06-29 11:14:32 浏览次数:3 分类:技术文章

本文共 1154 字,大约阅读时间需要 3 分钟。

当你使用 history 模式时,URL 就像正常的 url,例如 http://yoursite.com/user/id,也好看!

不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。

所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。

后端配置例子

注意:下列示例假设你在根目录服务这个应用。如果想部署到一个子目录,你需要使用 Vue CLI 的publicPath 选项 和相关的 router base property。你还需要把下列示例中的根目录调整成为子目录 (例如用 RewriteBase /name-of-your-subfolder/替换掉 RewriteBase /)。

Apache

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

nginx

location / {
try_files $uri $uri/ /index.html;}

原生 Node.js

const http = require('http')const fs = require('fs')const httpPort = 80http.createServer((req, res) => {
fs.readFile('index.html', 'utf-8', (err, content) => {
if (err) {
console.log('We cannot open "index.html" 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)})

转载地址:https://blog.csdn.net/zwhy123/article/details/110001265 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Vue项目页面跳转时,窗口上方显示进度条(Vue使用NProgress)
下一篇:VUE CLI 4.x 打包成APP后白屏解决办法&&打包APP教程

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月02日 12时58分41秒