redirectServedPathMiddleware.js 741 B

1234567891011121314151617181920212223242526
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. const path = require('path');
  9. module.exports = function createRedirectServedPathMiddleware(servedPath) {
  10. // remove end slash so user can land on `/test` instead of `/test/`
  11. servedPath = servedPath.slice(0, -1);
  12. return function redirectServedPathMiddleware(req, res, next) {
  13. if (
  14. servedPath === '' ||
  15. req.url === servedPath ||
  16. req.url.startsWith(servedPath)
  17. ) {
  18. next();
  19. } else {
  20. const newPath = path.join(servedPath, req.path !== '/' ? req.path : '');
  21. res.redirect(newPath);
  22. }
  23. };
  24. };