http 模块
-
引入
http
模块
添加一个核心的模块http
模块,负责处理接收浏览发送过来的数据;const http = require("http");
-
创建服务器
使用
createServer()
方法创建一个服务器const server = http.createServer();
-
监听数据
当浏览器发送过来请求后,就会触发 request 这个事件,这时会调用后面的回调函数;
req
表示请求对象,获取客户端的请求信息;res
表示相响应对象,给客户端发送响应信息
server.on("request", function(req, res) {
console.log("收到客户端的请求了");
const url = req.url; //获取请求路径
//if判断请求路径的不同,返回不同的响应结果
if (url == "/") res.end("这是首页");
//多次响应
//res.write('发送给客户端')
//write方法可以用来给客户端发送响应数据,可以使用多次
//res.end()//必须使用end结束响应,否则客户端会一直等待
//单次响应
//res.end('发送给客户端')
});
-
服务器启动
服务器启动后,自动调用该回调函数
server.listen(3000, "127.0.0.1", function() { console.log("服务器启动成功了..."); });
完整代码
const http = require("http");
const server = http.createServer();
server.on("request", function(request, response) {
const url = req.url; //获取请求路径
//if判断请求路径的不同,返回不同的响应结果
if (url == "/") res.end("这是首页");
//响应的数据只能是二进制数据(json)或者字符串
});
server.listen(3000, "127.0.0.1", function() {
console.log("服务器启动成功了...");
});
返回的数据
获取浏览器发送回来的内容,从而决定服务器给浏览器返回什么内容
const url=req.url;
'1.返回不同的内容'
if(url==='/'){res.end('这是网站首页')}
else if(url==='/test.html'){res.end('超文本标记语言')}else {res.end('页面不存在');}
'2.返回html内容'
if(url==='/'){res.end('<h1>这是网站首页</h2>')}
else if(url==='/test.html'){res.end('<h1>语言<h1>')}else {res.end('<h1>页面不存在<1>')}
'.返回完整html网页'
if(url==='/04test2.html'){
fs.readFile('./test.html','utf-8',function(err,data){
if(err){res.end('访问的内容有问题!')}
else{res.end(data);}
})}
else if(url==='/test.html'){res.end('<h1>语言<h1>')}else {res.end('<h1>页面不存在<h1>');}
//读取test.html文件中的内容
//readFile读取文件内容
//1.表示文件的路径;2.表示使用的编码
//3.文件读取完成后,会自动调用该函数,函数中第一个参数,存储的错误信息(err)
//从文件中读取出来得分内容全部保存在data整个参数中.