簡體   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