How to host an AngularJS app in Heroku using Node.js WITHOUT using yeoman?

混江龙づ霸主 提交于 2019-11-30 08:53:04

Well, I don't know why I got a down vote. But any way, I found my issue looking at this example.

The actual issue was that I was not making "public" the directory with express:

app.use(express.static(__dirname));

Here is the hello world

index.html

<!DOCTYPE html>
<html ng-app="main">
<head>
    <meta name="name" content="something">
    <title></title>
</head>
<body>
    <section ng-view=""></section>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js" type="text/javascript" charset="utf-8"></script>

    <script type="text/javascript" charset="utf-8">
    angular.module('main', ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider){
        console.log('hola');
        $routeProvider
        .when('/', {
            templateUrl: 'templates/index.html'
            ,controller: 'indexCtrl'
        })
        .when('/second', {
            templateUrl: 'templates/second.html'
            ,controller: 'secondCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
    }])
    .controller('indexCtrl', ['$scope', function ($scope){
        $scope.helloWorld = "Hello World";
    }])
    .controller('secondCtrl', ['$scope', function ($scope){
        $scope.helloWorld = "World Hello";
    }]);
    </script>
</body>
</html>

Server / index.js

var express = require('express'),
app = express();

app.use(express.static(__dirname));
app.get('/', function(req, res) {
    res.sendfile('index.html', {root: __dirname })
});
var server = app.listen(process.env.PORT || 80);

Procfile

web: node index.js

templates/index.html

<h1>{{ helloWorld }}<h1>
<a href="#/second" title="">Go to Second</a>

templates/second.html

<h1>{{ helloWorld }}<h1>
<a href="#/" title="">Go to First</a>

I hope this helps someone.

To answer my question. Yes, it is possible, what I was doing wrong is not making the templates(files) accessible. If you want to have extra security on what can be accessible you could create a folder called, for example, public. Then make that directory static:

app.use(express.static(__dirname + '/public'));

then you can also have different routes to communicate with your application even RESTfully. Like:

app.get('/users', function(req, res) {
    res.json({...});
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!