Nodejs 处理请求以及路由

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

处理Get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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");
});

结果

1
2
3
4
5
6
7
8
9
10
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请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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");
});

结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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}"
}
0%