前言
在 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) { arr.push(data); }); req.on("end", function() { console.log(Buffer.concat(arr).toString()); });});server.listen(3000, function() { console.log("server start 3000");});通过 req 对应的属性可以拿到请求行和请求首部的信息,请求体内的内容通过流操作来获取,其中 url 中存在多个有用的参数,我们自己处理会很麻烦,可以通过 NodeJS 的核心模块 url 进行解析。
const url = require("url");let str = "http://user:pass@ 发送了请求,并在客户端的回调中处理了响应(百度新闻页返回的数据),将处理后的内容通过我们自己 Node 服务器的 res 对象返回给了浏览器。总结
相信在读过本篇文章之后对搭建一个 Node 服务应该已经有了思路,为未来通过 Node 服务实现复杂的业务场景及数据的处理打下了一个基础,希望初学 Node 的小伙伴在看了这篇文章后能有所收获。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。