使用querystring.parse
来解析URL带来的键值对
。
处理Get请求
1const http = require("http");
2const querystring = require("querystring");
3
4
5const server = http.createServer((req, res) => {
6 console.log(req.method);
7 const url = req.url;
8 req.query = querystring.parse(url.split("?")[1]);
9 res.end(JSON.stringify(req.query));
10
11});
12
13server.listen(4000, () => {
14 console.log("4000");
15});
结果
1GET {{api}}/?a=eee&b=222
2
3---
4
5HTTP/1.1 200 OK
6Date: Fri, 19 Jul 2019 02:28:07 GMT
7Connection: close
8Content-Length: 21
9
10{"a":"eee","b":"222"}
处理Post请求
1const http = require("http");
2const server = http.createServer((req, res) => {
3 if (req.method === "POST") {
4 //req Data Format
5 console.log("req content-type", req.headers["content-type"]);
6 // Accept Data
7 let postData = "";
8 req.on("data", chunk => {
9 //chunk is binary
10 postData = postData + chunk.toString();
11 });
12 req.on("end", () => {
13 console.log(postData);
14 res.end(postData);
15 });
16 }
17});
18
19server.listen(4000, () => {
20 console.log("4000");
21});
结果
1POST {{api}} HTTP/1.1
2Content-Type: application/json
3
4{
5 "name":"张三",
6 "age": 54
7}
8
9---
10
11HTTP/1.1 200 OK
12Date: Fri, 19 Jul 2019 03:14:20 GMT
13Connection: close
14Content-Length: 38
15
16{
17 "name":"张三",
18 "age": 54
19}
路由预处理以及querystring
1const http = require("http");
2const querystring = require("querystring");
3
4const server = http.createServer((req, res) => {
5 const method = req.method;
6 const url = req.url;
7
8 const path = url.split("?")[0];
9 console.log("path: ", path);
10
11 const query = querystring.parse(url.split("?")[1]);
12 console.log("query: ", query);
13
14 res.setHeader("Content-type", "application/json"); //设置响应头的类型
15
16 const resData = {
17 method,
18 url,
19 path,
20 query
21 };
22
23 //GET
24
25 if (method === "GET") {
26 res.end(JSON.stringify(resData));
27 }
28
29 //POST
30
31 if (method === "POST") {
32 let postData = "";
33
34 req.on("data", chunk => {
35 postData += chunk.toString();
36 });
37
38 req.on("end", () => {
39 resData.postData = postData;
40 res.end(JSON.stringify(resData));
41 });
42 }
43});
44
45server.listen(4000, () => {
46 console.log("4000");
47});
结果
GET
1GET {{api}}/?a=eee&b=222
2
3HTTP/1.1 200 OK
4Content-type: application/json
5Date: Fri, 19 Jul 2019 05:46:50 GMT
6Connection: close
7Content-Length: 79
8
9{
10 "method": "GET",
11 "url": "/?a=eee&b=222",
12 "path": "/",
13 "query": {
14 "a": "eee",
15 "b": "222"
16 }
17}
POST
1POST {{api}}/a/b?a=eee&b=222 HTTP/1.1
2Content-Type: application/json
3
4{
5 "name":"张三",
6 "age": 54
7}
8
9HTTP/1.1 200 OK
10Content-type: application/json
11Date: Fri, 19 Jul 2019 05:47:42 GMT
12Connection: close
13Content-Length: 147
14
15{
16 "method": "POST",
17 "url": "/a/b?a=eee&b=222",
18 "path": "/a/b",
19 "query": {
20 "a": "eee",
21 "b": "222"
22 },
23 "postData": "{\n \"name\":\"张三\",\n \"age\": 54\n}"
24}