1. 创建最基本的服务器步骤
①导入http模块
②创建web服务器实例
③为服务器绑定request
事件,监听客户端的请求
④启动服务器
// 1、导入http模块
const http = require('http')
// 2、创建web服务器实例
const server = http.createServer()
// 3、为服务器绑定request事件,监听客户端的请求
server.on('request', function(req, res) {
console.log('有人在访问服务器')
})
// 4、启动服务器
server.listen(8085, function() {
console.log('服务器启动了');
})
2. req请求对象
只要服务器接收到了客户端的请求,就会调用server.on
为为服务器绑定的request事件处理函数,该函数的回调函数的第一个参数就是req请求对象
server.on('request', function(req, res) {
// req是请求对象,它包含了客户端相关的数据和属性,例如:
// req.url 是客户端请求的URL地址
// req.method 是客户端的 method 请求类型
console.log(req.url)
console.log(req.method)
})
3. res响应对象
只要服务器接收到了客户端的请求,就会调用server.on
为为服务器绑定的request事件处理函数,该函数的回调函数的第二个参数就是req请求对象
server.on('request', function(req, res) {
// res是响应对象,它包含了客户端相关的数据和属性,例如:
// 要发送给客户端的字符串
// res.end() 方法的作用: 向客户端发送指定内容,并结束本次请求
const str = 'you are welcome'
res.end(str)
})
4. 中文乱码问题
server.on('request', function(req, res) {
// 发送的内容中包含中文
// 为防止中文乱码,需设置响应头 'Content-Type', 'text/html; charset=utf-8'
const str = '你访问我干啥?'
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(str)
})
4. 根据不同的url响应不同的html内容
步骤:
① 获取请求的url地址
② 设置默认的响应内容为 404 Not Found
③ 对url做判断
④ 设置Content-type
响应头,防止中文乱码
⑤ 使用 res.end()
把内容响应给客户端
// 1、导入http模块
const http = require('http')
// 2、创建web服务器实例
const server = http.createServer()
// 3、为服务器绑定request事件,监听客户端的请求
server.on('request', function(req, res) {
let content = '<h1>404 Not Found</h1>'
const url = req.url
if(url === '/' || url === '/index.html') {
content = '<h1>我是首页</h1>'
}
res.setHeader('Content-type', 'text/html; charset=utf-8')
res.end(content)
})
// 4、启动服务器
server.listen(8085, function() {
console.log('服务器启动了')
})