1. 程式人生 > >NodeJs學習筆記(一)

NodeJs學習筆記(一)

輸出hello world

requestListener   請求處理函式,自動新增到 request 事件,函式傳遞兩個引數:

request:  請求物件。

response:   響應物件 ,收到請求後要做出的響應.

main.js
var  http  =  require('http'); //該方法屬於http模組,使用前需要引入http模組
http.createServer(function  (request,  response)  {  
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'}); //請求頭,狀態200為請求成功 
    if(request.url!=="/favicon.ico"){  //清除第2此訪問  
        console.log('訪問');  
        response.write('hello world');  
        response.end();//不寫則沒有http協議尾,但寫了會產生兩次訪問  
    }  
}).listen(8000);  
console.log('Server  running  at  http://127.0.0.1:8000/');  

呼叫函式

main.js

var http = require('http');
var otherFun = require('./modal/other.js');

http.createServer(function(request,response){
	response.writeHead(200,{'Content-Type':   'text/html;    charset=utf-8'});
	 if(request.url!=="/favicon.ico"){    //清除第2此訪問  
        fun1(response);//呼叫內部函式
        //呼叫外部函式,兩種方式:
        //第一種
		funName='fun2';
		otherFun[funName](response);
		otherFun['fun3'](response);
		//第二種
		otherFun.fun2(response);
		otherFun.fun3(response);
		
        response.end();   
    }  
	
}).listen(8000);

function fun1(res){
	console.log('輸出fun1');
	res.write('我是fun1');
	
}
other.js
module.exports = {
	fun2:function(res){
		res.write('我是fun2');
	},
	fun3:function(res){
		res.write('我是fun3');
	}
}

模組呼叫

main.js

var http = require('http');
var Teacher = require('./modal/Teacher.js');

http.createServer(function(request,response){
	response.writeHead(200,{'Content-Type':   'text/html;    charset=utf-8'});
	 if(request.url!=="/favicon.ico"){    //清除第2此訪問  
		teacher= new Teacher(1,'張三','8');
		teacher.enter();
		teacher.teach(response);
        response.end();   
    }  
	
}).listen(8000);

User.js
function User(id,name,age){
	this.id=id;
	this.name=name;
	this.age=age;
	this.enter = function(){
		console.log(this.name+"進入圖書館");
	}

}

module.exports = User;
Teacher.js
ar User= require('./User.js');
function Teacher(id,name,age){
	User.apply(this,[id,name,age]);
	this.teach = function(res){
		res.write(this.name+'在上課');
	}
}
module.exports=Teacher;

初步理解路由

main.js

var http = require('http');
var url = require('url');
var route = require('./route');
http.createServer(function(request,response){
        response.writeHead(200,    {'Content-Type':'text/html;charset=utf-8'});
        if(request.url!=="/favicon.ico"){
             var    pathname    =    url.parse(request.url).pathname;
      pathname    =    pathname.replace(/\//,    '');//替換掉前面的/
        route[pathname](request,response);
                response.end('');
        }
}).listen(8000);
console.log('Server    running    at    http://127.0.0.1:8000/'); 

route.js

module.exports={
	login:function(){
		console.log("我是登陸");
	},
	register:function(){
		console.log("我是註冊");
	}
}