javascript – 使用AngularJS和外部NodeJS服务器启用html5模式

所以我已经阅读了几乎所有关于这个主题的答案/问题,但我脑子里还有很多问题.

一,问题:

我有一个启用了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" />

我正在使用正在使用express的NodeJS服务器:

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');
  });
});

The thing is, I don’t have an index.html file on my server, neither do
I want to duplicate it on my server.

那么如何在不在我的服务器上存储html文件的情况下告诉Node正确处理请求?

我正在Heroku上托管Node应用程序,如果这有帮助的话.

最佳答案 当你说你不提供静态文件时,你是说node.js API不对吗?

我想你最终得到了两个截然不同的网址,让我们称之为http://api.com和http://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;
  }
}
点赞