NodeJS——http模块创建最简单的服务器

#http模块创建服务器 在nodejs的http模块中,http既可以创建服务器,也可以模拟浏览器向其他服务器发送请求 1、模拟浏览器 http.get(url,callback) 向服务器发请求 url 请求的url callback 回调函数,获取服务器端的响应 res x响应的对象 res.statusCode 获取响应的状态码 res.on(‘data’,function(chunk){ }) 监听服务器是否有数据传输 chunk:就是传输的数据,格式为buffer

//引入http模块
const http=require(http);
//向其他服务器发请求
//使用回调函数来获取响应
http.get(http://www.tmooc.cn,function(res){
          
   
	//res:响应的对象
	//console.log(res.statusCode);状态码
	//获取响应的数据
	//监听是否有数据传递
	res.on(data,function(chunk){
          
   
		console.log(chunk.toString());
	});

2、创建服务器

var app=http.createServer(); //创建web服务器
app.listen(8080);           //设置监听的端口
//监听浏览器的请求
app.on(request,function(req,res){
          
   
//req:请求的对象
    req.url   请求的url,端口号后的部分,表示要获取的内容
    req.method   请求的方法
//res:响应的对象
res.writeHead(状态码,头信息对象)  设置响应的状态码和头信息
res.write()  设置响应的内容
res.end()   结束并发送响应
});

例子:创建web服务器,监听端口8080,接收浏览器的请求,根据请求作出响应 /list 响应内容 ‘this is product list’ /index 响应内容 ‘this is homepage’ / 跳转到 /index /study 跳转到 http; 其他 响应状态 404 内容 not found

//引入http模块
const http=require(http);
//创建web服务器
var app=http.createServer();
//设置监听端口,监听浏览器的请求
app.listen(8080);

//事件:接收请求,监听请求
app.on(request,function(req,res){
          
   
	if(req.url==/list){
          
   
		res.wirte(this is product list);
		res.end();
	}else if(req.url==/index){
          
   
		res.write(this is homepage);
		res.end();
	}else if(req.url==/){
          
   
		res.writeHead(302,{
          
   Location:http://localhost:8080/index})
		res.end();
	}else if(req.url==/study){
          
   
		res.writeHead(302,{
          
   Location:http://baidu.com})
		res.end();
	}
});
经验分享 程序员 微信小程序 职场和发展