connect-history-api-fallback库的理解

2 篇文章 0 订阅
1 篇文章 0 订阅

connect-history-api-fallback库的理解

介绍

今天在搭建项目的时候遇到了一个问题,该项目是一个单页面应用,前端使用的是 React,用 react-router 做的前端路由,后端用的 express 做的 web 服务器,遇到的问题是通过页面点击进入页面没有问题,但是当通过地址栏输入URL的方式访问页面就会报 404 错误,google 之后发现了这个神奇的 js 库。github 上是这么介绍这个库的:

Single Page Applications (SPA) typically only utilise one index file that is accessible by web browsers: usually index.html. Navigation in the application is then commonly handled using JavaScript with the help of the HTML5 History API. This results in issues when the user hits the refresh button or is directly accessing a page other than the landing page, e.g. /help or /help/online as 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 Found message to the user.

单页面应用程序 (SPA) 通常使用一个 web 浏览器可以访问的索引文件,比如 index.html,然后,在 HTML5 History API 的帮助下(react-router 就是基于 History API 实现的),借助 JavaScript 处理应用程序中的导航。当用户单击刷新按钮或直接通过输入地址的方式访问页面时,会出现找不到页面的问题,因为这两种方式都绕开了 History API,而我们的请求又找不到后端对应的路由,页面返回 404 错误。
connect-history-api-fallback 中间件很好的解决了这个问题。具体来说,每当出现符合以下条件的请求时,它将把请求定位到你指定的索引文件(默认为 /index.html)。

  • 请求是Get请求
  • 请求的Content-Type类型是text/html类型
  • 不是直接的文件请求,即所请求的路径不包含.(点)字符
  • 不匹配option参数中提供的模式

使用方法

安装:

npm install --save connect-history-api-fallback

下面主要介绍下在express中的使用方法:

var history = require('connect-history-api-fallback');
var express = require('express');
var app = express();
app.use(history());

express 中使用的时候需要注意一点的是,该中间件必须要放在 express.static中间件的前面引入,否则会出现问题。

选项

使用的时候可以传入一个可选的参数,比如覆盖默认的索引文件:

history({
    index: '/default.html'
});

当请求url匹配 regex 模式时,重写索引。可以重写为静态字符串,也可以使用函数转换传入请求:

history({
    rewrites: [ rewrites: [
      { from: /\/soccer/, to: '/soccer.html'}{ from: /\/soccer/, to: '/soccer.html'}
    ] ]
});

结论

关于 connect-history-api-fallback 中间件的介绍就到这里,使用它很好的帮我解决了在开发单页面应用中遇到的问题,更多使用方法大家可以自行参考官方文档

更多精彩内容欢迎关注我的公众号!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值