NodeJS搭建搭建HTTP服务器的实现步骤服务器的实现步骤
前言前言
在 NodeJS 中用来创建服务的模块是 http 核心模块,本篇就来介绍关于使用 http 模块搭建 HTTP 服务器和客户端的方法,以
及模块的基本 API。
HTTP 服务器服务器
1、创建、创建 HTTP 服务器服务器
在 NodeJS 中,创建 HTTP 服务器可以与 net 模块创建 TCP 服务器对比,创建服务器有也两种方式。
方式 1:
const http = require("http");
const server = http.createServer(function(req, res) {
// ......
});
server.listen(3000);
方式 2:
const http = require("http");
const server = http.createServer();
server.on("request", function(req, res) {
// ......
});
server.listen(3000);
在 createServer 的回调和 request 事件的回调函数中有两个参数,req(请求)、res(响应),基于 socket,这两个对象都
是 Duplex 类型的可读可写流。
http 模块是基于 net 模块实现的,所以 net 模块原有的事件在 http 中依然存在。
const http = require("http");
const server = http.createServer();
// net 模块事件
server.on("connection", function(socket) {
console.log("连接成功");
});
server.listen(3000);
2、获取请求信息、获取请求信息
在请求对象 req 中存在请求的方法、请求的 url(包含参数,即查询字符串)、当前的 HTTP 协议版本和请求头等信息。
const http = require("http");
const server = http.createServer();
server.on("request", function(req, res) {
console.log(req.method); // 获取请求方法
console.log(req.url); // 获取请求路径(包含查询字符串)
console.log(req.httpVersion); // 获取 HTTP 协议版本
console.log(req.headers); // 获取请求头(对象)
// 获取请求体的内容
let arr = [];
req.on("data", function(data) {