使用HTTP模块创建一个服务器
首先来看一下示例图:
分为一下步骤:
- 1.导入http模块
- 2.创建一个服务器
- 3.读取文件路径(设置返回给用户看的内容)
- 4.开启服务器
为了防止中文乱码,一定要设置utf-8 切记! 切记! 切记!
// 1.导入http模块
const http=require('http')
// 2.创建一个服务器
// 这个方法有一个返回值,这个返回值就代表服务器
const server=http.createServer((request,response)=>{
// response.end("hellow world")
response.setHeader('Content-Type','text/html;charset=utf-8')
response.end("大家好,我是林俊杰,是一名歌星")
})
// 4.开启服务器
// 端口
server.listen(8087,()=>{
console.log('服务器开起了:8087')
})
通过web服务器读取网页返回给用户
端口号的取值为 0-65535 因为现在1023一下的端口号已经分配给了那些常用的应用程序,所以我们选择选取1023后面的端口号就行了
- 1.导入http, fs ,path模块
- 2.创建服务器
- 3.读文件返回
- 3.1拼接要读取的文件的路径
- 3.2读取这个文件的内容
- 4.开启服务器
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html{
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
body{
background: linear-gradient(to bottom,red, green,blue);
}
</style>
</head>
<body>
<div>这是一首简单的小情歌</div>
<p>唱着人们心肠的曲折</p>
</body>
</html>
js代码:
//导入http,fs,path模块
const fs=require('fs')
const http=require('http')
const path=require('path')
// 创建服务器
const server=http.createServer((request,response)=>{
// 读文件返回
// 拼接要读取的文件的路径
const fullPath=path.join(__dirname,'web','index.html')
// 读取这个文件的内容
fs.readFile(fullPath,'utf-8',(err,data)=>{
if(err==null){
response.end(data)
}else{
response.end('404')
}
})
})
// 4.开启服务器
server.listen(4399,()=>{
console.log("读取成功")
})
这样你通过访问我们的服务器地址 127.1.1.1:4399 就可以得到我们写的html页面了