vue-router踩坑:History模式下,打包后页面访问404
2018-07-09 18:37
603 查看
在开发vue单页应用时,遇到一个问题:
在history模式下,开发环境各页面访问正常,但是在生产环境(nodejs/Express服务器),只能访问首页,其他使用vue-router跳转的页面全部是404。而在hash模式下开发环境和生产环境路由跳转均无问题。
后来详细查看vue-router文档中关于history部分,提到中间件:connect-history-api-fallback。
var express = require('express');var history = require('connect-history-api-fallback');var app = express();app.use(history());
关于这个问题,connect-history-api-fallback文档中也有提及:
Single Page Applications (SPA) typically only utilise one index file that isaccessible by web browsers: usually
index.html. Navigation in the applicationis then commonly handled using JavaScript with the help of theHTML5 History API.This results in issues when the user hits the refresh button or is directlyaccessing a page other than the landing page, e.g.
/helpor
/help/onlineas the web server bypasses the index file to locate the file at this location.As your application is a SPA, the web server will fail trying to retrieve the file and return a 404 - Not Foundmessage to the user.
大致意思是:单页应用通常只有一个浏览器可以访问的index.html。但是如果使用history模式,用户直接访问或者刷新非index.html时,例如访问'/list',web服务器会绕过index.html,去'/list'位置找相应的页面,这样就会导致404。而connect-history-api-fallback中间件,会把访问地址改成'/',然后vue-router渲染对应的list组件。
与此类似的还有一个问题,在《JavaScript高级程序设计》第16章-16.4-历史状态管理 中有提到:在使用HTML5的状态管理机制时,请确保使用pushState()创造的每一个“假”URL,在Web服务器上都有一个真的、实际存在的URL与之对应。否则,单击“刷新”按钮会导致404错误。
相关文章推荐
- vue +vue-cli+vue router ,npm run build 打包完页面空白,不显示URL的#号router模式为history
- vue-router使用 history 模式刷新后404问题
- Vue下路由History模式打包后页面空白的解决方法
- 解决vue-router嵌套路由(子路由)在history模式下刷新无法渲染页面的问题
- nginx配置vue-router+webpack项目部署访问刷新出现404问题
- vue-router HTML5 History 模式(转自官网)
- vue小笔记 打包之后,刷新页面出现404的问题
- vue-cli 打包使用history模式的后端配置实例
- vue.js中利用router进行跳转(子页面刷新404问题)
- vue+webpack 打包文件 404 页面空白的解决方法
- react-router browserHistory刷新页面404问题解决方法
- vue-router无论是hash模式还是历史模式在ios微信浏览器中进入哪个页面复制链接或选择safari打开都是第一次进入的那个页面
- Vue-router本地服务器使用history出现找不到页面的问题解决方法
- Vue-router 中hash模式和history模式的区别
- vue-cli 打包 使用 history模式 的后端配置
- tomcat服务如何配置vue-router的history模式
- react,vue等部署单页面项目时,访问刷新出现404问题
- 详解如何将 Vue-cli 改造成支持多页面的 history 模式
- 解决element-ui中el-menu组件作为vue-router模式在刷新页面后default-active属性与当前路由页面不一致问题的方法
- vue-router踩坑之history模式的scrollBehavior