在开发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错误。




Logo

前往低代码交流专区

更多推荐