The http module is a module officially provided by Node.js to create a web server .
Through the http.createServer() method provided by the http module , an ordinary computer can be conveniently turned into a web server to provide web resource services to the outside world.
Create the most basic web server
- import http module
- Create a web server instance
- Bind the request event to the server instance and listen to the client's request
- start server
sample code
//1.导入http模块
const http = require('http')
//2.创建web服务器实例
const server = http.createServer()
//3.为服务器实例绑定request事件,监听客户端的请求
server.on('request',function(req,res){
console.log('Someone visit our web server')
//获取请求的url地址
const url = req.url
//设置默认的响应内容为404 Not found
let content = '404 Not found'
//判断用户请求的是否为/ 或 /index.html首页
//判断用户请求的是否为/about.html关于页面
if(url === '/' || url==='/index.html'){
content = '<h1>首页</h1>'
}else if(url==='/about.html'){
content = '<h1>关于页面</h1>'
}
//设置Content-Type响应头,防止中文乱码
res.setHeader('Content-Type','text/html;charset=utf-8')
//使用res.end()把内容响应给客户端
res.end(content)
})
//启动服务器
server.listen(8080,function(){
console.log('server running at http://127.0.0.1:8080')
})
Application examples:
There is a clock folder on the local disk, which contains html, css, and js files. When the html file is opened on the browser, a clock pattern is displayed. Requirement: Create a web server, use the content in the clock folder as the server resource, and when the client accesses the server, enter /index.html to load the clock pattern.
My local folder structure is as follows:
//1.1导入http模块
const http = require('http')
//1.2导入fs模块
const fs = require('fs')
//1.3导入path模块
const path = require('path')
//2.1创建web服务器
const server = http.createServer()
//2.2监听web服务器的request事件
server.on('request',(req,res) => {
// 3.1获取到客户端请求的url地址
// /clock/index.html
// /clock/index.css
// /clock/index.js
const url = req.url
// 3.2 把请求的url地址映射为具体文件的存放路径
let fpath = ''
if (url === '/'){
fpath = path.join(__dirname,'../clock/index.html')
}else{
fpath = path.join(__dirname,'../clock',url)
}
// 4.1 根据映射过来的文件路径读取文件的内容
fs.readFile(fpath,'utf8',(err,dataStr) => {
//4.2 读取失败,向客户端响应固定的"错误消息"
if (err) return res.end('404 Not found')
//4.3 读取文件成功,将读取成功的内容,响应给客户端
res.end(dataStr)
})
})
//2.3启动服务器
server.listen(8080, () => {
console.log('server running at http://127.0.0.1')
})