搭建一个http的服务器,用户处理用户发送的http请求,需要使用node提供的一个模块:http;
// 1 加载http模块
var http = require('http');
// 2.通过http模块下的CreatServer创建并且返回一个web服务器对象
var server = http.createServer(function(){
console.log('有客户端请求来了');
console.log(req);
});
server.on('error',function(err){
console.log(err);
});
server.on('listening',function(){
console.log('listening-----');
});
server.on('request',function(req,res){
console.log('有客户端请求来了');
console.log(req);
console.log('有客户端请求来了');
//console.log(req);
//console.log(res);
//把数据写入头信息当中,可以调用多次
res.setHeader('miaov','leo');
//写入头信息(状态码,描述文字,头信息),只能在当前调用中使用一次,并且在end介绍前
res.writeHead(200,'miaov',{
//告诉客户端我现在发送你的是什么类型的数据
'content-type':'text/html,charset=utf-8', //Hello
// 'content-type':'text/plain',//<h1>Hello</h1>
});
//发送一个数据块到响应正文中
//res.write("hello");
res.write('<h1>Hello</h1>');
//当所有正文和头信息发送完成以后调用该方法告诉服务器数据已经全部
//发送完成了,这个方法在每次发送完消息之后,必须调用,并且在最后调用
//如果在该方法中传入参数,会自动调用`write`方法,再调用`end`方法
res.end('<h1>Hello</h1>');
});
//3.端口号0-1024都被系统应用测试用完了
server.listen(8081,'localhost');
//console.log(server.address());
-------------------------打印--------------------------------------
/usr/local/bin/node server1.js
listening-----
有客户端请求来了
有客户端请求来了
![](https://img.haomeiwen.com/i2055354/42b4936f4fbd7516.png)
res.writeHead(200,'miaov',{
//告诉客户端我现在发送你的是什么类型的数据
'content-type':'text/html,charset=utf-8', //Hello
// 'content-type':'text/plain',//<h1>Hello</h1>
});
![](https://img.haomeiwen.com/i2055354/cc8bb1eb1587166a.png)
res.setHeader('miaov','leo');
![](https://img.haomeiwen.com/i2055354/5fb4088699a59c04.png)
网友评论