vue-router踩坑:History模式下,打包后页面访问404

在开发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. /help or /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错误。




  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值