http 模块是 Node.js 官方提供的、用来创建web服务器的模块,通过 http.createServer() 的方法,就能把一台普通的电脑,变成一台 Web 服务器,从而对外提供 Web 资源服务。
创建web服务器的基本步骤
步骤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(8080, function () {
console.log("server running at http://127.0.0.1:8080");
});
在终端打开和请求:
req请求对象
req是请求对象,它包含了与客户端相关的数据和属性;
req.url 是客户端的URL地址;
req.method 是客户端的method(get、post)请求类型;
const http = require("http");
const server = http.createServer();
server.on("request", (req) => {
const url = req.url;
const method = req.method;
const str = `Your request url is ${url}, and request method is ${method}`;
console.log(str);
});
server.listen(8080, () => {
console.log("server running at http://127.0.0.1:8080");
});
res响应对象
res是响应对象,它包含了与服务器相关的数据和属性;
要发送到客户端的字符串;
res.end()方法的作用:向客户端发送指定的内容,并结束这次请求的处理过程;
server.on("request", (req, res) => {
const url = req.url;
const method = req.method;
const str = `Your request url is ${url}, and request method is ${method}`;
console.log(str);
res.end(str);
解决中文乱码问题
当调用res.end() 方法,向客户端发送中文内容的时候,会出现乱码问题,此时,需要手动设置内容的编码格式:设置响应头Content-Type的值为text/html; charset=utf-8
server.on("request", (req, res) => {
const url = req.url;
const method = req.method;
const str = `您请求的url地址是${url},请求的类型为${method}`;
console.log(str);
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end(str);
});
根据不同的url响应不同的html内容
server.on("request", (req, res) => {
// 获取请求的 url 地址
let url = req.url;
// 设置默认的响应内容为 404 Not found
let content = "404 Not found!";
// 判断用户请求是否为 / 或 /index.html 首页
if (url === "/" || url === "/index.html") {
content = "<h1>首页</h1>";
}
// 判断用户是否为 /about.html 关于页面
else if (url === "/about.html") {
content = "<h1>关于页面</h1>";
}
// 设置 Content-Type 响应头,防止中文乱码
res.setHeader("Content-Type", "text/html; charset=utf-8");
// 把内容发送给客户端
res.end(content);
});