获取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实例,最后转为字符串

  1. import * as http from "http";
  2. import { IncomingMessage, ServerResponse } from "http";
  3. const server = http.createServer();
  4. server.on("request", (request: IncomingMessage, response: ServerResponse) => {
  5. /** const { url, method, httpVersion, headers } = request;
  6. console.log(`url: ${url}`);
  7. console.log(`method: ${method}`);
  8. console.log(`httpVersion: ${httpVersion}`);
  9. console.log(`headers: ${JSON.stringify(headers)}`);
  10. 仅做数据展示
  11. */
  12. const array: Buffer[] = [];
  13. request.on("data", (chunk: Buffer) => {
  14. array.push(chunk);
  15. });
  16. request.on("end", () => {
  17. const postRequestBody = Buffer.concat(array).toString();
  18. console.log(`postRequestBody: ${postRequestBody}`);
  19. response.end("hi" + "\n");
  20. });
  21. });
  22. server.listen(8888, () => {
  23. console.log(server.address());
  24. });

运行命令行

  1. yarn global add ts-node-dev
  2. ts-node-dev 文件路径

curl 发送POST请求

  1. curl -v -d 'hobby=games' http://localhost:8888

静态服务器搭建

path.resolve() 方法会将路径或路径片段的序列解析为绝对路径(从右至左,直至遇上绝对路径)

__dirname:当前模块的目录名
__filename:当前模块的文件名

new URL()解析request.url
new URL(request.url,http://${request.headers.host}`)`
返回如下对象
image.png

  1. import * as fs from "fs";
  2. import * as http from "http";
  3. import { IncomingMessage, ServerResponse } from "http";
  4. import * as p from "path";
  5. const server = http.createServer();
  6. const publicDir = p.resolve(__dirname, "public");
  7. let cacheAge = 3600 * 24 * 365;
  8. server.on("request", (request: IncomingMessage, response: ServerResponse) => {
  9. const { url: path, headers, method } = request;
  10. const { pathname } = new URL(path, `http://${headers.host}`);
  11. if (method !== "GET") {
  12. response.statusCode = 405;
  13. response.end();
  14. return;
  15. }
  16. let fileName = pathname.substr(1);
  17. if (fileName === "") {
  18. fileName = "index.html";
  19. }
  20. const fileType = fileName.split(".")[1];
  21. const fileTypeHash = {
  22. html: "text/html",
  23. css: "text/css",
  24. js: "text/javascript",
  25. png: "image/png",
  26. jpg: "image/jpeg",
  27. };
  28. response.setHeader("Content-Type", `${fileTypeHash[fileType]};charset=utf-8`);
  29. fs.readFile(p.resolve(publicDir, fileName), (error, data) => {
  30. if (error) {
  31. if (error.errno === -4058) {
  32. response.setHeader("Content-Type", "text/html;charset=utf-8");
  33. response.statusCode = 404;
  34. fs.readFile(p.resolve(publicDir, "4040.html"), (error, data) => {
  35. if (error) {
  36. response.end();
  37. }
  38. response.end(data);
  39. });
  40. } else if (error.errno === -4068) {
  41. response.statusCode = 403;
  42. response.end("你无权进行此访问");
  43. } else {
  44. response.statusCode = 404;
  45. response.end();
  46. }
  47. } else {
  48. console.log("访问成功");
  49. response.setHeader("Cache-Control", `public,max-age=${cacheAge}`);
  50. response.end(data);
  51. }
  52. });
  53. });
  54. server.listen(8888, () => {
  55. console.log("监听成功");
  56. });