搭建web服务器
一、http模块
这里我们使用 node 的 http 模块搭建 HTTP服务。下面是用到的主要方法:
1、创造服务器实例
/**
* 创造服务器实例
* @param {Function} callback 回调函数,有两个参数:
* request 客户端的HTTP请求
* response 服务器端的HTTP回应
*/
createServer(callback(request, response));
2、服务器实例的方法
/**
* 启动服务器监听指定端口
* @param {String} port 端口
* @param {String} host 主机名
* @param {Function} callback 回调函数
*/
listen(port,host,callback);
3、客户端的HTTP请求的属性
url 发出请求的网址
method HTTP请求的方法
headers HTTP请求的所有HTTP头信息
4、服务器端的HTTP回应的方法
writeHeader(key, value) 指定HTTP头信息
write(str) 指定HTTP回应的内容
end() 发送HTTP回应
5、引入fs模块,读取文件内容用来写入到HTTP回应
/**
* 读取文件
* @param {String} path 文件的路径
* @param {Function} callback 回调函数
*/
fs.readFile(path, callback(err, data));
6、代码如下:
/**
* @description: node服务配置文件
* @author: guang.shi <https://blog.youkuaiyun.com/guang_s>
* @date: 2019-04-10 10:02:24
*/
const http = require('http')
const path = require('path')
const fs = require('fs')
// 参数配置
const host = '127.0.0.1' // 设置主机名
const port = 8080 // 设置端口
const openPage = '/example/index.html' // 默认打开的页面
const rootPath = path.resolve(__dirname, './') // 文件的访问路径
// 创造一个服务器实例(req:客户端的HTTP请求 | res:服务器端的HTTP回应)
const server = http.createServer(function(req, res) {
const url = req.url // 客户端输入的url,如:输入 localhost:8080/index.html,那么 url = '/index.html'
const file = rootPath + url // 访问的文件路径
fs.readFile(file, function(err, data) {
if (err) {
res.writeHeader(404, {
'content-type': 'text/html;charset="utf-8"'
})
res.write('<h1>404错误</h1><p>你要找的页面不存在</p>')
res.end()
}
else {
res.writeHeader(200, {
'content-type': 'text/html;charset="utf-8"'
})
res.write(data)
res.end()
}
})
})
// 启动服务器监听指定端口
server.listen(port, host, function() {
console.log('\x1B[36m%s\x1B[0m', `服务器运行在: \n - http://${host}:${port} \n - http://${host}:${port}${openPage}`)
})
7、启动服务
node server.js
二、express模块
系列文章
【node使用】发布一个自己的npm包
【node使用】搭建一个web服务器
【node使用】package.json详解以及package-lock.json的作用
【node使用】path模块
【node使用】glob匹配模式
【node使用】fs模块
【node使用】实现console输出不同颜色