繁体   English   中英

配置sails服务器以使用html5Mode?

[英]configure sails server to work with html5Mode?

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

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

$locationProvider.html5Mode(true);

并且路由工作直到我刷新页面。

导航到http://localhost:1337/about工作。 我刷新并得到

{
  "status": 404
}

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

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

要在风帆中执行此操作,没有“切换”,您可以设置应用程序范围的策略,检查角度是否正在进行呼叫,或者浏览器是否正在进行呼叫并发送相应的文件,您可以看到下面的代码。 您必须确保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();
};

这是一个稍微不同的问题,但我之前的SO答案可能适用。 在SailsJS上刷新时找不到页面

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

您可以设置一个通配符路由到一个控制器方法,该方法将发送您的单页应用程序,或实际资产(如果存在)。 如果你有一个清晰的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文件)下,则将其发送.js ; 否则,发送index.html 有一些偏执路径检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM