当前位置: 首页 > 后端技术 > Node.js

新前端小姐姐问:vue路由历史模式刷新页面404问题

时间:2023-04-03 13:25:56 Node.js

摘要:vue-router默认的hash模式——使用url的hash来模拟一个完整的url,所以当url发生变化时,页面不会更改重新加载。本文分享自华为云社区《学习Vue Router,HTML5 History 模式,因为history模式刷新页面会出现404》,作者:DevFeng。Vue-router默认的hash模式——使用URL的hash来模拟一个完整的URL,所以当URL改变时,页面不会重新加载。如果不想要难看的hash,我们可以使用路由的history模式,它充分利用了history.pushStateAPI,可以在不重新加载页面的情况下完成URL跳转。constrouter=newVueRouter({mode:'history',routes:[...]})当你使用history模式时,URL就像一个普通的url,比如http://yoursite.com/user/id,还不错!不过要玩好这个模式,还需要后台配置支持。因为我们的应用是单页客户端应用,如果后台配置不正确,用户在浏览器中直接访问http://oursite.com/user/id时,会返回404,不好看.所以,你需要在服务器端添加一个涵盖所有情况的候选资源:如果URL没有匹配到任何静态资源,它应该返回相同的index.html页面,也就是你的应用所依赖的页面。后端配置示例注意:以下示例假设您从根目录为应用程序提供服务。如果要部署到子目录,则需要使用VueCLI的publicPath选项(opensnewwindow)和关联的路由器基础属性(opensnewwindow)。您还需要将以下示例中的根目录调整为子目录(例如将RewriteBase/替换为RewriteBase/name-of-your-subfolder/)。ApacheRewriteEngineOnRewriteBase/RewriteRule^index\.html$-[L]RewriteCond%{REQUEST_FILENAME}!-fRewriteCond%{REQUEST_FILENAME}!-dRewriteRule./index.html[L]除了mod_rewrite,你还可以使用FallbackResource(opensnewwindow)。nginxlocation/{try_files$uri$uri//index.html;}NativeNode.jsconsthttp=require('http')constfs=require('fs')consthttpPort=80http.createServer((req,res)=>{fs.readFile('index.html','utf-8',(err,content)=>{if(err){console.log('我们无法打开“index.html”文件。')}res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})res.end(content)})}).listen(httpPort,()=>{console.log('服务器侦听:http://localhost:%s',httpPort)})ExpressonNode.js对于Node.js/Express,考虑使用connect-history-api-fallback中间件(opensnewwindow)。在InternetInformationServices(IIS)上安装IISUrlRewrite(opensnewwindow),并在您网站的根目录中创建一个web.config文件,内容如下:Caddyrewrite{regexp.*to{path}/}Firebase主机在你添加到firebase.json:{"hosting":{"public":"dist","rewrites":[{"source":"**","destination":"/index.html"}]}}warning被警告,因为在这样做之后,你的服务器将不再返回404错误页面,因为将为所有路由返回index.html文件。为避免这种情况,您应该覆盖Vue应用程序中的所有路由案例,然后给出404页面。constrouter=newVueRouter({mode:'history',routes:[{path:'*',component:NotFoundComponent}]})或者,如果你使用Node.js服务器,你可以使用服务器端路由来匹配incomingURLs,当没有匹配到路由时返回404以实现回退。点击关注,第一时间了解华为云的新鲜技术~