Back
Featured image of post Nodejs 处理请求以及路由

Nodejs 处理请求以及路由

使用querystring.parse来解析URL带来的键值对

处理Get请求

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


const server = http.createServer((req, res) => {
  console.log(req.method);
  const url = req.url;
  req.query = querystring.parse(url.split("?")[1]);
  res.end(JSON.stringify(req.query));

});

server.listen(4000, () => {
  console.log("4000");
});

结果

GET {{api}}/?a=eee&b=222

---

HTTP/1.1 200 OK
Date: Fri, 19 Jul 2019 02:28:07 GMT
Connection: close
Content-Length: 21

{"a":"eee","b":"222"}

处理Post请求

const http = require("http");
const server = http.createServer((req, res) => {
  if (req.method === "POST") {
    //req Data Format
    console.log("req content-type", req.headers["content-type"]);
    // Accept Data
    let postData = "";
    req.on("data", chunk => {
      //chunk is binary
      postData = postData + chunk.toString();
    });
    req.on("end", () => {
      console.log(postData);
      res.end(postData);
    });
  }
});

server.listen(4000, () => {
  console.log("4000");
});

结果

POST {{api}} HTTP/1.1
Content-Type: application/json

{
    "name":"张三",
    "age": 54
}

---

HTTP/1.1 200 OK
Date: Fri, 19 Jul 2019 03:14:20 GMT
Connection: close
Content-Length: 38

{
    "name":"张三",
    "age": 54
}

路由预处理以及querystring

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];
  console.log("path: ", path);

  const query = querystring.parse(url.split("?")[1]);
  console.log("query: ", query);

  res.setHeader("Content-type", "application/json"); //设置响应头的类型

  const resData = {
    method,
    url,
    path,
    query
  };

    //GET

  if (method === "GET") {
    res.end(JSON.stringify(resData));
  }

    //POST

  if (method === "POST") {
    let postData = "";

    req.on("data", chunk => {
      postData += chunk.toString();
    });

    req.on("end", () => {
      resData.postData = postData;
      res.end(JSON.stringify(resData));
    });
  }
});

server.listen(4000, () => {
  console.log("4000");
});

结果

GET

GET {{api}}/?a=eee&b=222

HTTP/1.1 200 OK
Content-type: application/json
Date: Fri, 19 Jul 2019 05:46:50 GMT
Connection: close
Content-Length: 79

{
  "method": "GET",
  "url": "/?a=eee&b=222",
  "path": "/",
  "query": {
    "a": "eee",
    "b": "222"
  }
}

POST

POST {{api}}/a/b?a=eee&b=222 HTTP/1.1
Content-Type: application/json

{
    "name":"张三",
    "age": 54
}

HTTP/1.1 200 OK
Content-type: application/json
Date: Fri, 19 Jul 2019 05:47:42 GMT
Connection: close
Content-Length: 147

{
  "method": "POST",
  "url": "/a/b?a=eee&b=222",
  "path": "/a/b",
  "query": {
    "a": "eee",
    "b": "222"
  },
  "postData": "{\n    \"name\":\"张三\",\n    \"age\": 54\n}"
}
comments powered by Disqus