从节点http服务器提供Angular页面时出错

时间:2016-06-03 23:07:17

标签: angularjs node.js

我使用以下(server.js)创建节点http服务器以加载Angular页面(index.html)。

server.js

var http = require('http');
var fs   = require('fs');
var HOST = '127.0.0.1';
var PORT = 3000;

http.createServer(function (request, response) {
  response.writeHead(200, {
      'Content-Type': 'text/html',
      'Access-Control-Allow-Origin' : '*'});
  response.end(fs.readFileSync('index.html'));
}).listen(PORT, HOST);
console.log('Node server listening at http://' + HOST + ':' + PORT);

的index.html

<html lang="en" ng-app="planetApp">
  <head>
    <meta charset="utf-8" />
    <title>Planet App</title>

    <!-- Include external styles -->
    <link rel="stylesheet" href="css/styles.css" />

    <!-- Include external Angular Libs -->
    <script src="js/lib/angular.min.js"></script>
    <script src="js/lib/angular-route.min.js"></script>

    <!-- Include external custom JS files -->
    <script src="js/planetController.js"></script>
    <script src="js/planetFactory.js"></script>
    <script src="js/planetDirective.js"></script>
    <script src="js/planetApp.js"></script>
  </head>
  <body>
    <div ng-view></div>
  </body>
</html>

如果我从WAMP提供它,应用程序加载正常,但是当我从节点提供它时出现以下错误:

SyntaxError: expected expression, got '<'
<html lang="en" ng-app="planetApp">

我认为它可能与以下的templateURL有关:

planetApp.js

var planetApp = angular.module('planetApp', [
  'ngRoute',
  'planetController',
  'planetFactory',
  'planetDirective'
]);

// App Config - runs once to register controllers
planetApp.config(function($routeProvider) {
  $routeProvider.
    when('/', {
      templateUrl: '../templates/planet_list.html',
      controller: 'PlanetListCtrl'
    }).
    when('/:planetId', {
      templateUrl: '../templates/planet_detail.html',
      controller: 'PlanetDetailCtrl'
    }).
    otherwise({
      redirectTo: '/'
    });
});

有没有人知道如何解决这个问题,使用节点的http服务器(不是快递)?

感谢任何指导!

1 个答案:

答案 0 :(得分:0)

解决以下问题:

<强> server.js

var http = require('http');
var fs   = require('fs');
var HOST = '127.0.0.1';
var PORT = 3000;

http.createServer(function (request, response) {
  var url = request.url;
  url = url.substring(1, url.length);
  response.writeHead(200, {
      'Content-Type': 'text/html',
      'Access-Control-Allow-Origin' : '*'});
  response.end(fs.readFileSync(url));
}).listen(PORT, HOST);
console.log('Node server listening at http://' + HOST + ':' + PORT);