使用http模块创建一个服务器
- 1.导入http模块
- 2.创建一个服务器
- 3.设置返回给用户看的内容
- 4.开启服务器
//使用内置模块http来创建一个服务器
//1.导入http模块
const http = require( 'http' );
//2.创建一个服务器
//这个方法有一个返回值,返回值就代表这个服务器
const server = http.createServer((request,response)=>{
//3.设置返回给用户看的内容
// response .end('hellow world!')
//如果想要返回去的中文不乱码,那就要设置响应头.
response. setHeader( 'Content-Type', ' text/html;charset=utf-8 ');
response.end('初次见面,请多关照!')
});
//4.开启服务器
//端口
server.listen(8087,()=>{
console.log('服务器开启了:8087');
})
web服务器读取网页返回给用户
- 1.导入http, fs ,path模块
- 2.创建服务器
- 3.读文件返回
- 3.1拼接要读取的文件的路径
- 3.2读取这个文件的内容
- 4.开启服务器
html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html{
margin: 0px;
padding: 0px;
height: 100%;
overflow: hidden;
}
body{
background: linear-gradient(to bottom ,red,green,blue);
}
</style>
</head>
<body>
<div>这是一个寂寞的天</div>
<p>下着有些伤心的雨</p>
</body>
</html>
js部分
//1.导入http, fs ,path模块
const fs = require('fs' );
const http = require( 'http' );
const path = require( 'path' );
//2.创建服务器
const server = http.createServer((request,response)=>{
//3.读文件返回
//3.1拼接要读取的文件的路径
const fullPath = path. join(__dirname ,'web', 'index.html ')
//3.2读取这个文件的内容
fs . readFile(fullPath, 'utf-8' , (err, data)=>{
if (err == null){
//3.3 返回给用户
response.end(data);
} else {
response.end('404')
}
})
})
//4.开启服务器
//端口
server.listen(4399,()=>{
console.log('服务器开启了:4399');
})