簡體   English   中英

使用AngularJS和外部NodeJS服務器啟用html5模式

[英]Enabling html5 mode with AngularJS and a external NodeJS server

所以我已經閱讀了幾乎所有關於這個主題的答案/問題,但我腦子里還有很多問題。

一,問題:

我有一個啟用了html5的AngularJS應用程序,所以我可以擺脫'#'符號。

$locationProvider.html5Mode({ enabled: true, requireBase: true });
$locationProvider.hashPrefix('!');

這是我的index.html中的重要部分:

<!DOCTYPE html>
<html ng-app="application" ng-controller="ApplicationController as app">
  <head>
    <meta name="fragment" content="!">

    <title>LivingRoomArt</title>

    <meta charset="UTF-8">
    <base href="/index.html" />

我正在使用正在使用expressNodeJS服務器:

router.route('/events')
  .post(authController.isAuthenticated, eventController.postEvent)
  .get(eventController.getEvents);

// Register all our routes with /api
app.use('/api', router);

// Start the server
app.listen(process.env.PORT || 5000);

所以,通常的問題:

重新加載后,我從服務器獲得404。 我在這里得到了這個概念,到處都是建議的解決方案:

  // This route deals enables HTML5Mode by forwarding missing files to the index.html
  app.all('/*', function(req, res) {
    res.sendfile('index.html');
  });
});

問題是,我的服務器上沒有index.html文件,也不想在我的服務器上復制它。

那么如何在不在我的服務器上存儲html文件的情況下告訴Node正確處理請求?

我正在Heroku上托管Node應用程序,如果這有幫助的話。

當你說你不提供靜態文件時,你是說node.js API不對嗎?

我想你最終得到了兩個截然不同的網址,讓我們稱之為http://api.comhttp://client.com

我不明白為什么你的API應該處理404.你在瀏覽器中加載http://api.com並期待你的index.html嗎? 如果它確實是你的用例,我建議在你的API中聲明一個簡單的路由,如:

app.all('/*', function (req, res) {
   res.redirect('http://client.com');
});

這會將您之前路線聲明未捕獲的所有請求重定向到您的客戶網站。


然后,有兩種選擇:

如果服務於您的靜態文件的服務器是使用express的另一個Node.Js服務器,那么您可以完美地執行sendfile ,因為您現在可以訪問index.html

如果您正在使用Nginx(我強烈推薦,如果您不這樣做)靜態,您可以執行這樣的配置,將所有失敗的請求(丟失的文件/路由)重定向到index.html

server {
  listen 80;

  root /app/www;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM