【问题标题】:configure sails server to work with html5Mode?配置sails 服务器以使用html5Mode?
【发布时间】:2014-07-08 17:12:40
【问题描述】:

我有一个 angular-sails 应用程序,我想从 URL 中删除哈希

我将此添加到我的客户app.config

$locationProvider.html5Mode(true);

在我刷新页面之前,路由一直有效。

导航到http://localhost:1337/about 有效。我刷新并得到

{
  "status": 404
}

来自 Sails 服务器。如何配置sails 以使用angularjs html5Mode?​​p>

【问题讨论】:

    标签: javascript angularjs sails.js angular-ui-router


    【解决方案1】:

    要使用 HTML5Mode,您需要您的服务器设置只提供您的根(或“index.html”)文件。 “web.com/index.html”。在我看来,最好将 Sails 应用程序和 Angular 前端分开以单独交付。这样,您可以轻松设置为您的 Angular 客户端前端提供服务的 Web 服务器,仅在非 AJAX 调用上提供 index.html。

    要在sails 中执行此操作,没有“开关”,您可以设置一个应用范围的策略来检查角度是否正在拨打电话或浏览器是否正在拨打电话并发送适当的文件,您可以查看下面的代码。您必须确保 angular 正在设置以下标题 X-Requested-With = XMLHttpRequest

    应用政策

    module.exports = function(req, res, next) {
    
      // Checks if this is an ajax request 
      // If True then skip this and return requested content
      // If False then return the index (or root) page  
      if (if !req.isAjax) {
        return res.view("/index");
      }
    
      return next();
    };
    

    【讨论】:

    • 我这里有问题,当我重新加载任何页面时(除了 (/))我得到 404。
    • 您有可以在某处发布的基本设置示例吗?
    • 我只在 app.js 上启用 html5mode 角度,在上面添加了这个策略并启用“*”:isAjax;在政策中。
    【解决方案2】:

    这是一个略有不同的问题,但我之前有一个可能适用的 SO 答案。 Page not found when refreshed on SailsJS

    您遇到了这个问题,因为当您重新加载页面时,sails 正在响应,并且它对您的角度路线一无所知。

    【讨论】:

      【解决方案3】:

      您可以设置通配符路由到控制器方法,该方法将发送您的单页应用程序或实际资产(如果存在)。如果您有一个明确的 URL 前缀,例如 /admin 在我的例子中,问题就不会那么严重了。这是我正在使用的:

      routes.js:

      'GET /admin/*': 'AdminController.index'
      

      AdminController.js:

      var path = require('path');
      var fs = require('fs');
      
      module.exports = {
          index: function(req, res) {
              var requestedPath = req.url;
              var resolvedPath = path.resolve(requestedPath);
              if (resolvedPath.indexOf('/admin') !== 0) {
                  res.send(403);
              } else {
                  var publicRoot = sails.config.paths.public;
                  var fullPath = path.join(publicRoot, resolvedPath);
                  fs.exists(fullPath, function(exists) {
                      if (exists) {
                          res.sendfile(resolvedPath, { root: publicRoot });
                      } else {
                          res.sendfile('/admin/index.html', { root: publicRoot });
                      }
                  });
              }
          }
      };
      

      如果资产确实存在于公共区域下(如.js 文件),请将其发送下来;否则,请发送index.html。带有一些偏执的路径检查。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-03
        相关资源
        最近更新 更多