connect-history-api-fallback库的理解

connect-history-api-fallback库的理解

  • connect-history-api-fallback库的理解
    • 介绍
    • 使用方法
    • 选项
    • 结论

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中间件的介绍就到这里,使用它很好的帮我解决了在开发单页面应用中遇到的问题,更多使用方法大家可以自行参考官方文档。

你可能感兴趣的:(javascript,nodejs,express)