You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

160 lines
4.9 KiB

3 months ago
  1. <h1 align="center">connect-history-api-fallback</h1>
  2. <p align="center">Middleware to proxy requests through a specified index page, useful for Single Page Applications that utilise the HTML5 History API.</p>
  3. <h2>Table of Contents</h2>
  4. <!-- TOC depthFrom:2 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 -->
  5. - [Introduction](#introduction)
  6. - [Usage](#usage)
  7. - [Options](#options)
  8. - [index](#index)
  9. - [rewrites](#rewrites)
  10. - [verbose](#verbose)
  11. - [htmlAcceptHeaders](#htmlacceptheaders)
  12. - [disableDotRule](#disabledotrule)
  13. <!-- /TOC -->
  14. ## Introduction
  15. Single Page Applications (SPA) typically only utilise one index file that is
  16. accessible by web browsers: usually `index.html`. Navigation in the application
  17. is then commonly handled using JavaScript with the help of the
  18. [HTML5 History API](http://www.w3.org/html/wg/drafts/html/master/single-page.html#the-history-interface).
  19. This results in issues when the user hits the refresh button or is directly
  20. accessing a page other than the landing page, e.g. `/help` or `/help/online`
  21. as the web server bypasses the index file to locate the file at this location.
  22. As your application is a SPA, the web server will fail trying to retrieve the file and return a *404 - Not Found*
  23. message to the user.
  24. This tiny middleware addresses some of the issues. Specifically, it will change
  25. the requested location to the index you specify (default being `/index.html`)
  26. whenever there is a request which fulfills the following criteria:
  27. 1. The request is a `GET` or `HEAD` request
  28. 2. which accepts `text/html`,
  29. 3. is not a direct file request, i.e. the requested path does not contain a
  30. `.` (DOT) character and
  31. 4. does not match a pattern provided in options.rewrites (see options below)
  32. ## Usage
  33. The middleware is available through NPM and can easily be added.
  34. ```
  35. npm install --save connect-history-api-fallback
  36. ```
  37. Import the library
  38. ```javascript
  39. var history = require('connect-history-api-fallback');
  40. ```
  41. Now you only need to add the middleware to your application like so
  42. ```javascript
  43. var connect = require('connect');
  44. var app = connect()
  45. .use(history())
  46. .listen(3000);
  47. ```
  48. Of course you can also use this piece of middleware with express:
  49. ```javascript
  50. var express = require('express');
  51. var app = express();
  52. app.use(history());
  53. ```
  54. ## Options
  55. You can optionally pass options to the library when obtaining the middleware
  56. ```javascript
  57. var middleware = history({});
  58. ```
  59. ### index
  60. Override the index (default `/index.html`). This is the request path that will be used when the middleware identifies that the request path needs to be rewritten.
  61. This is not the path to a file on disk. Instead it is the HTTP request path. Downstream connect/express middleware is responsible to turn this rewritten HTTP request path into actual responses, e.g. by reading a file from disk.
  62. ```javascript
  63. history({
  64. index: '/default.html'
  65. });
  66. ```
  67. ### rewrites
  68. Override the index when the request url matches a regex pattern. You can either rewrite to a static string or use a function to transform the incoming request.
  69. The following will rewrite a request that matches the `/\/soccer/` pattern to `/soccer.html`.
  70. ```javascript
  71. history({
  72. rewrites: [
  73. { from: /\/soccer/, to: '/soccer.html'}
  74. ]
  75. });
  76. ```
  77. Alternatively functions can be used to have more control over the rewrite process. For instance, the following listing shows how requests to `/libs/jquery/jquery.1.12.0.min.js` and the like can be routed to `./bower_components/libs/jquery/jquery.1.12.0.min.js`. You can also make use of this if you have an API version in the URL path.
  78. ```javascript
  79. history({
  80. rewrites: [
  81. {
  82. from: /^\/libs\/.*$/,
  83. to: function(context) {
  84. return '/bower_components' + context.parsedUrl.pathname;
  85. }
  86. }
  87. ]
  88. });
  89. ```
  90. The function will always be called with a context object that has the following properties:
  91. - **parsedUrl**: Information about the URL as provided by the [URL module's](https://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost) `url.parse`.
  92. - **match**: An Array of matched results as provided by `String.match(...)`.
  93. - **request**: The HTTP request object.
  94. ### verbose
  95. This middleware does not log any information by default. If you wish to activate logging, then you can do so via the `verbose` option or by specifying a logger function.
  96. ```javascript
  97. history({
  98. verbose: true
  99. });
  100. ```
  101. Alternatively use your own logger
  102. ```javascript
  103. history({
  104. logger: console.log.bind(console)
  105. });
  106. ```
  107. ### htmlAcceptHeaders
  108. Override the default `Accepts:` headers that are queried when matching HTML content requests (Default: `['text/html', '*/*']`).
  109. ```javascript
  110. history({
  111. htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
  112. })
  113. ```
  114. ### disableDotRule
  115. Disables the dot rule mentioned above:
  116. > […] is not a direct file request, i.e. the requested path does not contain a `.` (DOT) character […]
  117. ```javascript
  118. history({
  119. disableDotRule: true
  120. })
  121. ```