Nodejs--url模块


由于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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM