2016년 1월 28일 목요일

[NodeJS] html read

$ npm init

$ npm install express fs --save


  • package.json
  • node_module
  • app
    • index.html
    • data.json


  • server.js


0. Packgage.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
{
  "name""app1",
  "version""1.0.0",
  "description""first app",
  "main""server.js",
  "scripts": {
    "test""echo \"Error: no test specified\" && exit 1",
    "start""node server.js"
  },
  "author""jteve",
  "license""MIT",
  "dependencies": {
    "express""^4.13.4",
    "fs""0.0.2"
  }
}
 
cs

1. Server.js 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var express = require('express');
var app = express();
var fs = require('fs');
 
 
app.use(express.static('app'));
 
app.listen(3000,function(){
    console.log('server start 3000');
});
 
app.get('/'function(req,res){
    fs.readFile('app/index.html'function(error,data){
        if(error){
            console.log(error);
        }
        else{
            res.writeHead(200,{'Content-Type':'text/html'});
            res.end(data);
        }
    });        
});
 
cs
2. index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
<!DOCTYPE html>
<html >
  <head>
    <meta charset="utf-8">
 
  </head>
  <body ng-app='app'>
     <div ng-controller='DataCtrl'>
       <button ng-click='getTestHttp()'>Http Call </button>
       <h2>{{dataStr}}</h2>
     </div>
 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
     <script>
     var app  = angular.module('app',[]);
 
     app.controller("DataCtrl"function($scope, $http){
       $scope.getTestHttp = function(){
           $http({
             method:'GET',
             url:'data.json'
           }).success( function(data, status, headers, config){
             console.log("success" );
             console.dir(data);
           }).error( function(data, status, headers, config){
             console.log("error" );
           });
       };
     });
     </script>
   </body>
 </html>
 
cs



댓글 없음:

댓글 쓰기