weikee94 / blog-api

Node.js 从零开发web server博客项目
0 stars 0 forks source link

04 博客项目接口 #1

Open weikee94 opened 4 years ago

weikee94 commented 4 years ago

// Init Server

const http = require("http");
const server = http.createServer((req, res) => {
  res.end("Hello World");
});
server.listen(8000);
weikee94 commented 4 years ago

Handle GET request

const http = require("http");
const querystring = require("querystring");

const server = http.createServer((req, res) => {
  console.log(req.method); // GET
  const url = req.url; // full url
  req.query = querystring.parse(url.split("?")[1]); // 解析querystring
  res.end(JSON.stringify(req.query)); // 将querystring 返回
});

server.listen(8000);
weikee94 commented 4 years ago

Handle POST request


// POST request
const http = require("http");
const server = http.createServer((req, res) => {
  if (req.method === "POST") {
    // data format
    console.log("content-type", req.headers["content-type"]);
    // receive data
    let postData = "";
    // using chunk 数据流模式
    req.on("data", (chunk) => {
      postData += chunk.toString();
    });
    req.on("end", () => {
      console.log(postData);
      res.end("hello world");
    });
  }
});
server.listen(8000);
weikee94 commented 4 years ago

综合示例

const http = require("http");
const querystring = require("querystring");

const server = http.createServer((req, res) => {
  const method = req.method;
  const url = req.url;
  const path = url.split("?")[0];
  const query = querystring.parse(url.split("?")[1]);

  // 设置返回格式为 JSON
  res.setHeader("Content-type", "application/json");

  // 返回的数据
  const resData = {
    method,
    url,
    path,
    query,
  };

  if (method === "GET") {
    res.end(JSON.stringify(resData));
  }
  if (method === "POST") {
    let postData = "";
    req.on("data", (chunk) => {
      postData += chunk.toString();
    });
    req.on("end", () => {
      resData.postData = postData;
      // return data
      res.sendDate(JSON.stringify(resData));
    });
  }
});

server.listen(8000);