简体   繁体   中英

Nodejs/Express with Angular - 404 error

I've been trying to learn the MEAN stack and wanted to do an application to test it out. The aim was to have a static variable (in this case 'hello') displayed by Angular in the HTML, I can't seem to get my $scope variable in my controller to display, having looked in the developer console on my browser I saw 'GET 127.0.0.1:3000/app.js 404 not found'.

This is my node server using express:

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

app.get('/', function(req, res){

        res.sendFile(__dirname + '/views/index.html');
});



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

This is my index.html file (a directory below in /views):

 <!DOCTYPE html>
<html ng-app="myModule">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/
 angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>

<body>
<h1>Sucess!</h1>

        <div ng-controller="myController">
                <p>Angular test: {{ message }}</p>
        </div>
</body>

And this is my app.js file containing my module and controller (also in /views):

var myApp = angular.module('myModule', []);

    myApp.controller('myController', ['$scope',
function($scope) {

    $scope.message = 'hello';

}]);

I'd be very grateful if anyone could help out!

You will have to serve all the files, for example using express.static , not just index.html :

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM