获取POST请求体
注:静态服务器并不接受POST请求http.createServer()
创建一个http.Server类的实例
监听request事件,每当有请求时触发回调函数
回调函数接收(request :IncomingMessage,response :ServerResponse)=>{…}
request监听data事件(该事件继承自IncomingMessage的父类stream.Readable ),会在流将数据块传到后触发回调,回调函数接收chunk
request再监听end事件(同样继承自stream.Readable),流中没有数据可消费时触发
用Buffer.concat将Buffer构成的数组,拼接成一个新Buffer实例,最后转为字符串
import * as http from "http";
import { IncomingMessage, ServerResponse } from "http";
const server = http.createServer();
server.on("request", (request: IncomingMessage, response: ServerResponse) => {
/** const { url, method, httpVersion, headers } = request;
console.log(`url: ${url}`);
console.log(`method: ${method}`);
console.log(`httpVersion: ${httpVersion}`);
console.log(`headers: ${JSON.stringify(headers)}`);
仅做数据展示
*/
const array: Buffer[] = [];
request.on("data", (chunk: Buffer) => {
array.push(chunk);
});
request.on("end", () => {
const postRequestBody = Buffer.concat(array).toString();
console.log(`postRequestBody: ${postRequestBody}`);
response.end("hi" + "\n");
});
});
server.listen(8888, () => {
console.log(server.address());
});
运行命令行
yarn global add ts-node-dev
ts-node-dev 文件路径
curl 发送POST请求
curl -v -d 'hobby=games' http://localhost:8888
静态服务器搭建
path.resolve()
方法会将路径或路径片段的序列解析为绝对路径(从右至左,直至遇上绝对路径)
__dirname:当前模块的目录名
__filename:当前模块的文件名
new URL()解析request.urlnew URL(request.url,
http://${request.headers.host}`)`
返回如下对象
import * as fs from "fs";
import * as http from "http";
import { IncomingMessage, ServerResponse } from "http";
import * as p from "path";
const server = http.createServer();
const publicDir = p.resolve(__dirname, "public");
let cacheAge = 3600 * 24 * 365;
server.on("request", (request: IncomingMessage, response: ServerResponse) => {
const { url: path, headers, method } = request;
const { pathname } = new URL(path, `http://${headers.host}`);
if (method !== "GET") {
response.statusCode = 405;
response.end();
return;
}
let fileName = pathname.substr(1);
if (fileName === "") {
fileName = "index.html";
}
const fileType = fileName.split(".")[1];
const fileTypeHash = {
html: "text/html",
css: "text/css",
js: "text/javascript",
png: "image/png",
jpg: "image/jpeg",
};
response.setHeader("Content-Type", `${fileTypeHash[fileType]};charset=utf-8`);
fs.readFile(p.resolve(publicDir, fileName), (error, data) => {
if (error) {
if (error.errno === -4058) {
response.setHeader("Content-Type", "text/html;charset=utf-8");
response.statusCode = 404;
fs.readFile(p.resolve(publicDir, "4040.html"), (error, data) => {
if (error) {
response.end();
}
response.end(data);
});
} else if (error.errno === -4068) {
response.statusCode = 403;
response.end("你无权进行此访问");
} else {
response.statusCode = 404;
response.end();
}
} else {
console.log("访问成功");
response.setHeader("Cache-Control", `public,max-age=${cacheAge}`);
response.end(data);
}
});
});
server.listen(8888, () => {
console.log("监听成功");
});