http模块
作用:创建web服务器
const http = require(‘http’)
1,创建web服务实例
const server = http.createServer()
2,监听请求
server.on(‘request’,callback)
request 事件名字
callback是一个回调函数 两个行参
行参1:request 简写req 请求对象 里面包含请求对应地址携带的所有数据
行参2:response 简写res 响应对象 里面提供了用于响应的方法和属性
3,设置监听的端口号
server.listen(端口号,callback)
callback 回调函数 正常提醒用户监听成功即可
// 案例:手写一个服务器软件,启动后要求用户访问根“/”输出`hello world`,用户访问`/html5`输出`2021`
// a. 导入http模块
const http = require("http");
// b. 创建web服务器实例
const server = http.createServer();
// c. 监听请求
server.on("request", (req, res) => {
// 在这里设置如何响应用户的请求
// 获取用户访问的地址
// console.log(req);
let url = req.url;
// 判断
if (url === "/") {
// 输出响应
res.end("hello world");
}
if (url === "/html5") {
res.end("2021");
}
// ...
});
// d. 设置监听的端口号
server.listen(8080, () => {
console.log("服务器正在 http://127.0.0.1:8080 上奔跑!");
});
创建静态资源服务器
// a. 导入http模块
const http = require("http");
const path = require("path");
const fs = require("fs");