数据请求的方式不同,解析请求的方法也相应地有区别。
这里先分析原生node.js如何处理get数据请求,在express和koa框架中还会再提到这个内容。
当我们使用表单GET数据的时候,数据会在url地址栏中以user=tom&pass=123456&age=8
的形式显示,同样,我们在后台获取到的数据也是这种xxx=xxx&xxx=xxx的形式,那么就需要我们处理获得的数据,方便以后使用。
1 2 3 4 5 6
| <form action="http://localhost:8080" method="get"> 用户:<input type="text" name="user"><br> 密码:<input type="password" name="pass"><br> <input type="submit" value="提交"> </form>
|

1 2 3 4 5 6 7 8
| const http = require('http'); http.createServer(function(req, res) { console.log(req.url); res.write(); res.end(); }).listen(8080); console.log("server running");
|
在页面填写用户名为nikkkki,密码为123456,服务器端获得的信息如下:

这里需要注意的是,上图显示的返回信息为两条字符串,相当于传回了两条req.url信息。
我们希望获得的数据格式是json,那么我们有几种方法可以处理req.url:
第一种方法:完全依赖字符串原生方法来处理(非常不推荐)
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'); http.createServer(function(req, res) { let GET = {}; if(req.url.indexOf('?') > -1) { let arr1 = req.url.split('?'); let arr2 = arr1[1].split("&"); url = arr1[0]; for(let i of arr2) { let arr3 = i.split('='); GET[arr3[0]] = arr3[1]; } else { var url = req.url; } } console.log(url, GET); res.end(); }).listen(8080); console.log("server running");
|
输出结果为

第二种方法:引入querystring
模块
querystring
模块用来解析URL查询字符串,它主要用于界定”&”和”=”两个字符,querystring.parse(str,sep.eq,option)
第一个参数为要查询的字符串,第二、三个参数为要界定的字符,默认’&’和’=’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const http = require('http'); const querystring = require('querystring');
http.createServer(function(req, res) { let GET= {}; if(req.url.indexOf('?') > -1) { let arr = req.url.split('?'); url = arr[0]; GET = querystring.parse(arr[1]); } else { var url = req.url; } console.log(url, GET); res.end(); }).listen(8080); console.log("server running");
|
输出结果是

第三种方法:引入url
模块
用url.parse
方法会返回一个URL对象,如果要获取表单提交的信息,我们可以获取其中的query属性
1 2 3 4 5 6 7 8 9 10 11 12 13
| const http = require('http'); const urlLib = require('url');
http.createServer(function(req, res) { let obj = urlLib.parse(req.url, true);
let url = obj.pathname; let GET = obj.query;
console.log(url, GET); res.end(); }).listen(8080); console.log("server running");
|
输出结果如下:

如果不选取query或pathname属性,obj解析出来的url对象整体数据如下:

三种方法的输出结果一样,都可以达到将表单提交数据转化为json数据的效果。
