【node.js】03-http模块

目录

一、什么是http模块

二、创建基本的WEB服务器

三、req请求对象

四、res响应对象

五、根据不同的url响应不同的JSON内容


一、什么是http模块

        http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。通过 http 模块提供的 http.createServer() 方法,就能方便的把一台普通的电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务。

二、创建基本的WEB服务器

步骤:

1. 导入http 模块
2. 创建 web 服务器实例
3. 为服务器实例绑定 request 事件,监听客户端的请求
4. 启动服务器

代码:

//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.')
})

//4. 启动服务器
server.listen(80, function() {
	console.log('Server running at http://127.0.0.1:80')
})

三、req请求对象

        只要服务器接收到了客户端的请求,就会调用通过 server.on() 为服务器绑定的 request 事件处理函数。如果想在事件处理函数中,访问与客户端相关的数据或属性,可以使用如下的方式:

const http = require('http')
const server = http.createServer()

//req是请求对象,包含了与客户端相关的数据和属性
server.on('request', req => {
	const url = req.url //客户端请求的URL地址
	const method = req.method //客户端的请求类型
	console.log(`Your request url is ${url}, and request method is ${method}`)
})

server.listen(80, () => {
	console.log('Server running at http://127.0.0.1:80')
})

此时运行代码,然后用postman发一个post请求:

 可以看到服务端打印信息如下:

四、res响应对象

        在服务器的 request 事件处理函数中,如果想访问与服务器相关的数据或属性,可以使用如下的方式:

当使用res.end()向客户端发送中文的时候回出现中文乱码问题,这时候需要设置中文编码格式:

五、根据不同的url响应不同的JSON内容

步骤:

1. 获取请求的 url 地址

2. 设置默认的响应内容为 404 Not found

3. 判断用户请求,响应不同的JSON

4. 设置 Content-Type 响应头,防止中文乱码

5. 使用 res.end()把内容响应给客户端

代码:

const http = require('http')
const server = http.createServer()

server.on('request', (req, res) => {
	//1. 获取请求的URL地址
	const url = req.url

	//2. 设置默认的响应内容
	let content = '404 Not Found'

	//3.判断用户请求响应JSON
	if (url === '/') {
		content = { name: '小红', age: 18 }
	} else {
		content = { name: '小黑', age: 20 }
	}
	//4. 设置响应头
	res.setHeader('Content-Type', 'application/json')

	//5. 向客户端响应的JSON内容
	res.end(JSON.stringify(content))
})

server.listen(80, () => {
	console.log('Server running at http://127.0.0.1:80')
})

猜你喜欢

转载自blog.csdn.net/ChaoChao66666/article/details/131911808