2016-05-04 41 views
1

我想通过node-express运行角度应用程序。Nodejs Express不加载脚本文件

文件结构

AngularNode 
    public 
     /core.js 
     /index.html 
    project.json 
    server.js 

server.js

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

app.get('*', function(req, res) { 
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end) 
}); 

// listen (start app with node server.js) ====================================== 
app.listen(8000); 
console.log("App listening on port 8000"); 

的index.html

<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>  
    <script src="./core.js"></script> 
........ 

个4 core.js

angular.module('MySystem',[]) 
.controller('AppController',['$scope',function($scope){ 
    $scope.Name ="Testing Text"; 
}]); 

当我试图运行使用node server.js此此应用,index.html文件得到正确装入,然而这不检测或装载core.js文件。和我收到以下错误

Uncaught SyntaxError: Unexpected token <   core.js:1 
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.5/$injector/modulerr?p0=MySystem&p1=Error%3…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.5%2Fangular.min.js%3A19%3A381) angular.js:38 

现在,当我直接从资源管理器中打开index.html文件,这是工作时相同的代码,我从core.js移动到内嵌HTML,<head>下与<script>块是加工。

我不确定,为什么core.js当我运行节点时没有检测或加载。

回答

1

得到了与一些修改解决方案:

加线server.js app.use(express.static(__dirname + '/public'));线 var app = express();

案例修正后(人均l'f')功能从res.sendfile('./public/index.html');res.sendFile('./public/index.html');

现在我可以看到core.js被检测到并且工作正常。

+0

还有一观测和修正: 随着'res.sendFile上面的代码( './公共/ index.html中');',**节点控制台** _throws ERROR_ '类型错误:路径必须绝对或指定根res.sendFile' 修复按照'('./public/index.html',{" root':__dirname})修改此修改;'' – Kenz

0

app.get('*', function(req, res) {是所有get请求的所有规则,也将匹配./core.js请求。所以对于./core.js你的快车应用程序也将发送HTML文件。

您应该使用express.static代替:

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

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