Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS's $routeProvider templateUrl is always returning 404 using Express

So the issue is that AngularJS's $routeProvider/ngRoute is not working as I need it to. I can't get it to display the respective .html page on its route. I'm always getting GET http://localhost:3000/home.html 404 (Not Found) when I try to load the template in my index.ejs page.

I have tried many variations of paths to get the .html to load but I haven't been successful. I even created home.html for each folder in the app to see if it'll grab anything but nothing worked. ng-include doesn't work when injected directly into the html either.

/app.js simplified: original code uses express.router()

var express = require('express');
var app = express();
var path = require('path');
var ejs = require('ejs');

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req,res,next) {
    res.render('index', { page: 'index' });
});

app.listen(3000,function(){ console.log('3k'); });

/views/index.ejs

<!DOCTYPE html>

<html lang="en" ng-app="App">
<head>
    <meta charset="UTF-8">
    <title>WHY???</title>
</head>
<body>

    <div class="main">
        <div ng-view></div>
    </div>

    <script src="/vendor/angular/angular.js"></script>
    <script src="/vendor/angular-route/angular-route.js"></script>
    <script src="/angular/angularApp.js"></script>
</body>
</html>

/public/angular/angularApp.js

var App = angular.module('App',['ngRoute']);

App.config(['$routeProvider', function($routeProvider) {

    $routeProvider
        .when('/', {
            templateUrl: 'views/index/home.html'
        })
        .when('/team', {
            templateUrl: '/views/index/team.html'
        })
        .when('/faq', {
            templateUrl: '/views/index/faq.html'
        })
        .otherwise({
            redirectTo: '/'
        })
}]);

home.html, team.html, and faq.html all have simple lines of code for testing purposes. Example: <h1> This is home.html </h1>

Folder Structure

app.js

public/
|-vendor/
|-angular/
| |-angularApp.js

views/
|-index.ejs
|
|-index/
| |-home.html
| |-faq.html
| |-team.html
like image 469
Phil C Avatar asked Sep 27 '22 00:09

Phil C


1 Answers

Node/Express is serving everything statically from the "public" folder. You need to set all of your URLs relative to the public directory.Your index folder should be moved into public.

app.js

public/
|-vendor/
|-angular/
| |-angularApp.js
|views/
| |-index/
| | |-home.html
| | |-faq.html
| | |-team.html

views/
|-index.ejs

This folder structure should work. Also fix this:

    when('/', {
        templateUrl: '/views/index/home.html'
    })
like image 82
Moshe Karmel Avatar answered Sep 29 '22 13:09

Moshe Karmel