WakaChewbacca WakaChewbacca - 3 months ago 7
AngularJS Question

Trouble with $routeProvider in page served by Express.js

I am trying to build my first Express.js/Angular application but am having trouble with

$routeProvider
on the page being served by the Express.js application. Here is the
server.js
:

var express = require('express');
var PORT = process.env.PORT || 3000;
var app = express();
app.get('/', function (req, res) {
res.sendFile(__dirname + '/client/views/index.html');
});

app.listen(3000, function () {
console.log("I'm listening");
});


The
index.html
page renders and includes the following Angular code:

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

app.config(function ($routeProvider) {
$routeProvider
.when('/main', {
templateUrl:'/client/views/main.html'
});
});


Yet when navigating to
localhost:3000/#/main
, nothing is injected into the
<ng-view>


Any advice would be greatly appreciated.

Answer

Having encountered this issue before I found a solution by telling express to serve files statically.

app.use(express.static('client'));

This tells express to send files from the 'client' directory as-is. This is used for files such as images, CSS & client side JavaScript. When referencing a file statically, paths are relative to the specified static directory so /client/views/main.html would be /views/main.html.

You can view the documentation for the express static middle ware here.

Comments