由於GET請求直接被嵌入在路徑中,URL是完整的請求路徑,包括了?后面的部分,因此你可以手動解析后面的內容作為GET請求的參數。
url 模塊中的 parse 函數可以用於解析url中的參數。
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
參數使用說明如下:
-
urlStr - 需要接收的url字符串。
-
parseQueryString - 為true時將使用查詢模塊分析查詢字符串,默認為false。
-
shashesDenoteHost
-默認為false,//foo/bar 形式的字符串將被解釋成 { pathname: ‘//foo/bar' }
-如果設置成true,//foo/bar 形式的字符串將被解釋成 { host: ‘foo', pathname: ‘/bar' }
urlcontent.js
1 var http = require('http'); 2 var url = require('url'); 3 var util = require('util'); 4 5 http.createServer(function (req, res) { 6 res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); 7 res.write('url:'+req.url+'\n\n'); 8 res.write(util.inspect(url.parse(req.url, true))+'\n\n'); 9 10 var params = url.parse(req.url, true).query; 11 res.write("name:" + params.name + '\n'); 12 res.write("age:" + params.age + '\n'); 13 14 var pathname = url.parse(req.url, true).pathname; 15 res.write('pathname:' + pathname + '\n'); 16 17 var path = url.parse(req.url, true).path; 18 res.write('path:' + path); 19 res.end(); 20 }).listen(3000);
我們在瀏覽器中輸入以下地址:localhost:3000/user?name=dragon&age=18
顯示結果如下:
下面我們新建一個form表單,再來模擬一下。
index.html
1 <html> 2 <head> 3 <title>test</title> 4 </head> 5 <body> 6 <form action="http://localhost:3000" method="GET"> 7 <table border="0"> 8 <tr> 9 <td>username:</td> 10 <td><input type="text" name="username"><br/></td> 11 </tr> 12 <tr> 13 <td>password:</td> 14 <td><input type="text" name="password"><br/></td> 15 </tr> 16 <tr> 17 <td align="center" colspan="2"><input type="submit" name="" value="提交"></td> 18 </tr> 19 </table> 20 </form> 21 </body> 22 </html>
server.js
1 var http = require("http"); 2 var url = require("url"); 3 var server = http.createServer(function (req, res) { 4 5 var queryObj = url.parse(req.url, true).query; 6 var username = queryObj.username; 7 var password = queryObj.password; 8 9 res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); 10 res.write('server received form request:\n\n'); 11 res.write('username:'+username+'\n\n'+'password:'+password); 12 res.end(); 13 }); 14 server.listen(3000);
運行server.js,然后打開index.html