8889841cREADME.md000066600000011607150513221140006026 0ustar00

connect-history-api-fallback

Middleware to proxy requests through a specified index page, useful for Single Page Applications that utilise the HTML5 History API.

Table of Contents

- [Introduction](#introduction) - [Usage](#usage) - [Options](#options) - [index](#index) - [rewrites](#rewrites) - [verbose](#verbose) - [htmlAcceptHeaders](#htmlacceptheaders) - [disableDotRule](#disabledotrule) ## Introduction 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](http://www.w3.org/html/wg/drafts/html/master/single-page.html#the-history-interface). 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. This tiny middleware addresses some of the issues. Specifically, it will change the requested location to the index you specify (default being `/index.html`) whenever there is a request which fulfills the following criteria: 1. The request is a `GET` or `HEAD` request 2. which accepts `text/html`, 3. is not a direct file request, i.e. the requested path does not contain a `.` (DOT) character and 4. does not match a pattern provided in options.rewrites (see options below) ## Usage The middleware is available through NPM and can easily be added. ``` npm install --save connect-history-api-fallback ``` Import the library ```javascript var history = require('connect-history-api-fallback'); ``` Now you only need to add the middleware to your application like so ```javascript var connect = require('connect'); var app = connect() .use(history()) .listen(3000); ``` Of course you can also use this piece of middleware with express: ```javascript var express = require('express'); var app = express(); app.use(history()); ``` ## Options You can optionally pass options to the library when obtaining the middleware ```javascript var middleware = history({}); ``` ### index 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. 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. ```javascript history({ index: '/default.html' }); ``` ### rewrites 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. The following will rewrite a request that matches the `/\/soccer/` pattern to `/soccer.html`. ```javascript history({ rewrites: [ { from: /\/soccer/, to: '/soccer.html'} ] }); ``` 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. ```javascript history({ rewrites: [ { from: /^\/libs\/.*$/, to: function(context) { return '/bower_components' + context.parsedUrl.pathname; } } ] }); ``` The function will always be called with a context object that has the following properties: - **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`. - **match**: An Array of matched results as provided by `String.match(...)`. - **request**: The HTTP request object. ### verbose 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. ```javascript history({ verbose: true }); ``` Alternatively use your own logger ```javascript history({ logger: console.log.bind(console) }); ``` ### htmlAcceptHeaders Override the default `Accepts:` headers that are queried when matching HTML content requests (Default: `['text/html', '*/*']`). ```javascript history({ htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] }) ``` ### disableDotRule Disables the dot rule mentioned above: > […] is not a direct file request, i.e. the requested path does not contain a `.` (DOT) character […] ```javascript history({ disableDotRule: true }) ``` lib/index.js000066600000006311150513221140006756 0ustar00'use strict'; var url = require('url'); exports = module.exports = function historyApiFallback(options) { options = options || {}; var logger = getLogger(options); return function(req, res, next) { var headers = req.headers; if (req.method !== 'GET' && req.method !== 'HEAD') { logger( 'Not rewriting', req.method, req.url, 'because the method is not GET or HEAD.' ); return next(); } else if (!headers || typeof headers.accept !== 'string') { logger( 'Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.' ); return next(); } else if (headers.accept.indexOf('application/json') === 0) { logger( 'Not rewriting', req.method, req.url, 'because the client prefers JSON.' ); return next(); } else if (!acceptsHtml(headers.accept, options)) { logger( 'Not rewriting', req.method, req.url, 'because the client does not accept HTML.' ); return next(); } var parsedUrl = url.parse(req.url); var rewriteTarget; options.rewrites = options.rewrites || []; for (var i = 0; i < options.rewrites.length; i++) { var rewrite = options.rewrites[i]; var match = parsedUrl.pathname.match(rewrite.from); if (match !== null) { rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req); if(rewriteTarget.charAt(0) !== '/') { logger( 'We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url ); } logger('Rewriting', req.method, req.url, 'to', rewriteTarget); req.url = rewriteTarget; return next(); } } var pathname = parsedUrl.pathname; if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && options.disableDotRule !== true) { logger( 'Not rewriting', req.method, req.url, 'because the path includes a dot (.) character.' ); return next(); } rewriteTarget = options.index || '/index.html'; logger('Rewriting', req.method, req.url, 'to', rewriteTarget); req.url = rewriteTarget; next(); }; }; function evaluateRewriteRule(parsedUrl, match, rule, req) { if (typeof rule === 'string') { return rule; } else if (typeof rule !== 'function') { throw new Error('Rewrite rule can only be of type string or function.'); } return rule({ parsedUrl: parsedUrl, match: match, request: req }); } function acceptsHtml(header, options) { options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*']; for (var i = 0; i < options.htmlAcceptHeaders.length; i++) { if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) { return true; } } return false; } function getLogger(options) { if (options && options.logger) { return options.logger; } else if (options && options.verbose) { // eslint-disable-next-line no-console return console.log.bind(console); } return function(){}; } LICENSE000066600000002102150513221140005542 0ustar00The MIT License Copyright (c) 2022 Ben Blackmore and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.package.json000066600000001525150513221140007033 0ustar00{ "name": "connect-history-api-fallback", "version": "2.0.0", "description": "Provides a fallback for non-existing directories so that the HTML 5 history API can be used.", "keyswords": [ "connect", "express", "html5", "history api", "fallback", "spa" ], "engines": { "node": ">=0.8" }, "main": "lib/index.js", "files": [ "lib" ], "scripts": { "test": "jest && eslint lib/*.js test/*.js" }, "repository": { "type": "git", "url": "http://github.com/bripkens/connect-history-api-fallback.git" }, "author": { "name": "Ben Ripkens", "email": "bripkens@gmail.com" }, "contributors": [ "Craig Myles (http://www.craigmyles.com)" ], "license": "MIT", "devDependencies": { "eslint": "^5.16.0", "jest": "^24.8.0", "sinon": "^7.3.2" } }