使用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。 我在这里得到了这个概念,到处都是build议的解决scheme:
// This route deals enables HTML5Mode by forwarding missing files to the index.html app.all('/*', function(req, res) { res.sendfile('index.html'); }); });
事情是,我的服务器上没有index.html文件,我也不想在服务器上复制它。
那么如何告诉Node正确处理请求而不在我的服务器上存储html文件呢?
如果这有帮助,我在Heroku上托pipeNode应用程序。
当你说你不提供静态文件,你是说node.js API是不正确的?
我想你最终有两个不同的url,我们称他们为http://api.com
和http://client.com
。
我不明白为什么你的API应该处理404。你是否在浏览器中加载了http://api.com
并期待你的index.html
? 如果这真的是你的用例,我会build议一个简单的路由在你的API中声明,如:
app.all('/*', function (req, res) { res.redirect('http://client.com'); });
这将redirect到您的客户网站没有通过您以前的路线声明抓住的所有请求。
那么,有两个select:
如果提供静态文件的服务器是使用express的另一个Node.Js服务器,则可以完美地执行sendfile
,因为您现在可以访问index.html
如果你正在使用Nginx,(我强烈build议,如果你不这样做的话),你可以这样做,将所有失败的请求(丢失的文件/路由)redirect到index.html
server { listen 80; root /app/www; index index.html; location / { try_files $uri $uri/ /index.html; } }