SFRA Server-side Javascript - Source: app_storefront_base/cartridge/controllers/RedirectURL.js menu

SFRA / Server-side JS / Source: app_storefront_base/cartridge/controllers/RedirectURL.js

  1. 'use strict';
  2. /**
  3. * @namespace RedirectURL
  4. */
  5. var server = require('server');
  6. /**
  7. * RedirectURL-Start : The RedirectURL-Start endpoint handles URL redirects
  8. * @name Base/RedirectURL-Start
  9. * @function
  10. * @memberof RedirectURL
  11. * @param {category} - non-sensitive
  12. * @param {serverfunction} - get
  13. */
  14. server.get('Start', function (req, res, next) {
  15. var URLRedirectMgr = require('dw/web/URLRedirectMgr');
  16. var redirect = URLRedirectMgr.redirect;
  17. var location = redirect ? redirect.location : null;
  18. var redirectStatus = redirect ? redirect.getStatus() : null;
  19. if (!location) {
  20. res.setStatusCode(404);
  21. res.render('error/notFound');
  22. } else {
  23. if (redirectStatus) {
  24. res.setRedirectStatus(redirectStatus);
  25. }
  26. res.redirect(location);
  27. }
  28. next();
  29. });
  30. /**
  31. * RedirectURL-Hostname : The RedirectURL-Hostname endpoint handles Hostname-only URL redirects
  32. * @name Base/RedirectURL-Hostname
  33. * @function
  34. * @memberof RedirectURL
  35. * @param {querystringparameter} - Location - optional parameter to provide a URL to redirect to
  36. * @param {category} - non-sensitive
  37. * @param {serverfunction} - get
  38. */
  39. server.get('Hostname', function (req, res, next) {
  40. var URLUtils = require('dw/web/URLUtils');
  41. var url = req.querystring.Location.stringValue;
  42. var hostRegExp = new RegExp('^https?://' + req.httpHost + '(?=/|$)');
  43. var location;
  44. if (!url || !hostRegExp.test(url)) {
  45. location = URLUtils.httpHome().toString();
  46. } else {
  47. location = url;
  48. }
  49. res.redirect(location);
  50. next();
  51. });
  52. module.exports = server.exports();