//导入node.js内置的http模块,通过该模块提供的方法来创建服务器程序
const http = require('http')
const fs = require('fs')
const path = require('path')
//创建http服务器(对象),然后将该服务器保存到变量myserver中
const myserver = http.createServer()
//启动http服务器
myserver.listen(3000,function(){
console.log('http服务器启动成功,服务器地址是http://localhost:3000')
})
//监听浏览器的请求(报文),当有一个请求(报文)发送到本服务器时,就会触发request事件
//本服务器通过监听request事件,来对浏览器的请求进行处理,并将处理结果响应(报文)的形式发送给浏览器
myserver.on('request',function(req,res){
//function回调函数的第一个参数req是一个IncomingMessage类的实例对象,该对象包含了与请求(报文)相关的信息
//第二个参数res是ServerResponse类的实例对象(可写流),该对象包含了与响应(报文)相关的信息
console.log('浏览器发送了一个请求')
// res.write('hello http server!')
//设置响应头告诉浏览器给它的是中文信息
res.setHeader('Content-Type','text/html;charset=utf-8')
// res.write('<h1 style="color:green;">hello http server!</h1>')
//向浏览器发送响应的最后,一定要调用end方法,结果响应
// res.end()
//生成要发送给浏览器的html文件的绝对路径
const filename = path.join(__dirname,'index.html')
fs.readFile(filename,'utf-8',function(error,data) {
if(error != null) {
console.log('网页文件读取失败!')
//向浏览器发送错误提示
res.write('<h1>服务器内部错误(错误状态码:5000)!</h1>')
}
else {
res.write(data)
res.end()
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
border: 1px solid red;
border-collapse: collapse;
}
tr,th,td{
border: 1px solid red;
text-align: center;
}
</style>
</head>
<body>
<table style="border:1px solid red;width: 500px; border-collapse: collapse;">
<tr>
<th>编号</th><th>姓名</th><th>年龄</th>
</tr>
<tr>
<th>1</th><th>小明</th><th>21</th>
</tr>
<tr>
<th>2</th><th>小芳</th><th>24</th>
</tr>
<tr>
<th>3</th><th>小杰</th><th>20</th>
</tr>
</table>
</body>
</html>