输出hello world
requestListener 请求处理函数,自动添加到 request 事件,函数传递两个参数:
main.jsrequest: 请求对象。
response: 响应对象 ,收到请求后要做出的响应.
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("我是注册");
}
}