http模块
一、什么是http模块
- http模块是官方提供,用来创建web服务器的模块。通过提供的http.createServer(),就可以将普通电脑变为服务器。
- 导入:const http = require('http');
二、创建web服务器
- 导入模块
- 创建web服务器实例
- 服务器实例绑定request时间,监听客户端请求
- 启动服务器
点击查看代码
const http = require('http');
const server = http.createServer();
// 监听请求
server.on('request',function(request,response){
console.log('Someone visit our server');
});
// 启动服务器
server.listen(8080,function(){
console.log('server running at 127.0.0.1');
});
三、req请求对象
- 包含了与客户端相关的数据和属性
点击查看代码
const http = require('http');
const server = http.createServer();
// 监听请求
server.on('request',function(req){
let url = req.url;
let method = req.method;
console.log('Someone visit our server');
let str = `Your request url is ${url} and request method is ${method}`
console.log(str)
});
// 启动服务器
server.listen(8080,function(){
console.log('server running at 127.0.0.1');
});
四、res响应对象
- 访问与服务器相关的数据和属性
点击查看代码
const http = require('http');
const server = http.createServer();
// 监听请求
server.on('request',function(req,res){
let url = req.url;
let method = req.method;
console.log('Someone visit our server');
// 防止中文乱码
res.setHeader('Content-Type','text/html; charset=utf-8');
let str = `Your request url is ${url} and request method is ${method}`
console.log(str)
// 向客户端发送特定的内容
res.end(str)
});
// 启动服务器
server.listen(8080,function(){
console.log('server running at 127.0.0.1');
});
五、根据不同的url返回不同的html内容
- 获取url地址
- 设置默认返回内容-404
- 判断用户是否访问的是/或/index.html首页
- 判断用户是否访问的是/about.html页面
- 设置Content-Type响应头,防止中文乱码
- 使用res.end()将内容返回给用户浏览器
点击查看代码
const http = require('http');
const server = http.createServer();
server.on('request',(req,res)=>{
const url = req.url;
let content = '<h1>404 Not Found!</h1>';
if(url === '/' || url === '/index.html'){
content = '<h1>首页</h1>';
}else if(url === '/about.html'){
content = '<h1>详情页</h1>';
}
res.setHeader('Content-Type','text/html; charset=utf-8');
res.end(content);
});
server.listen(8080,()=>{
console.log('Server running at http://127.0.0.1');
});
案例-实现clock时钟的web服务器
- 把文件的实际存放路径,作为每个资源的请求url地址
点击查看代码
const fs = require('fs');
const path = require('path');
const http = require('http');
const server = http.createServer()
server.on('request',(req,res)=>{
const url = req.url;
let fPath = '';
if(url === '/'){
fPath = path.join(__dirname,'./clock/index.html');
}else{
fPath = path.join(__dirname,'./clock',url);
}
// 请求的地址映射为本地文件的存放位置
//const fPath = path.join(__dirname,url);
let content = '<h1>404 NOT FOUND!</h1>';
fs.readFile(fPath,'utf-8',(err,dataStr)=>{
if(err){
res.end(content);
}
res.end(dataStr);
});
});
server.listen(8080,()=>{
console.log('Server running at http://127.0.0.1:8080/');
});