【笔记】Nodejs的Web服务器

前言

Nodejs通过内置的http模块实现Web服务器

创建web服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 引入模块
const http = require("http");

// 定义端口号
const port = 80;

// 创建对象
const app = http.createServer();

// 定义路由,处理请求
app.on("/", function (req, resp) {
// 接收请求,返回响应
resp.end("");
});

// 绑定端口,启动服务器
app.listen(port, function () {
// 启动成功后执行的代码
console.log(`http://127.0.0.1:${port}`)
});

请求

获取资源路径

1
req.url;

获取请求方法

1
req.method;

响应

返回响应

  • 响应数据给客户端,并结束本次请求
1
resp.end("");

设置响应头

<key>:响应头键
<value>:响应头值

1
resp.setHeader("<key>", "<value>");

解决响应数据的中文乱码

1
resp.setHeader("Content-Type", "text/html; charset=utf-8");

完成

参考文献

哔哩哔哩——黑马程序员
哔哩哔哩——前端开发专业教程