前言
在 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@www.pandashen.com:8080/src/index.html?a=1&b=2#hash";// parse 方法帮助我们解析 url 路径let obj = url.parse(str, true);console.log(obj);// {// protocol: 'http:',// slashes: true,// auth: 'user:pas',// host: 'www.pandashen.com:8080',// port: '8080',// hostname: 'www.pandashen.com',// hash: '#hash',// search: '?a=1&b=2',// query: '{ a: '1', b: '2' }',// pathname: '/src/index.html'// path: '/src/index.html?a=1&b=2',// href: 'http://user:pass@www.pandashen.com:8080/src/index.html?a=1&b=2#hash' }
新闻热点
疑难解答
图片精选