手机版
你好,游客 登录 注册
背景:
阅读新闻

node.js 接收get请求

[日期:2012-02-06] 来源:Linux社区  作者:dellheng [字体:大 中 小]

Get 请求的相关方法一定在http.ServerRequest下,ServerRequest有data、end、close3个事件,method、url、headers、trailers、httpVersion、connection6个属性,setEncoding、pause、resume3个方法。

url属性下有一段说明描述了怎么解析get请求:

request.url#

Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:

GET /status?name=ryan HTTP/1.1\r\n Accept: text/plain\r\n \r\n

Then request.url will be:

'/status?name=ryan'

If you would like to parse the URL into its parts, you can use require('url').parse(request.url). Example:

node> require('url').parse('/status?name=ryan') { href: '/status?name=ryan', search: '?name=ryan', query: 'name=ryan', pathname: '/status' }

If you would like to extract the params from the query string, you can use therequire('querystring').parse function, or pass true as the second argument to require('url').parse. Example:

node> require('url').parse('/status?name=ryan', true) { href: '/status?name=ryan', search: '?name=ryan', query: { name: 'ryan' }, pathname: '/status' }
说明中提到了require('url')和require('querystring') 可以分别查看API的URL和Query Strings小节

按照说明试一下吧(node> 表示 在命令行里敲代码)


那就结合 hello world 写一个动态的hello world

[Javascript]
  1. var http = require('http');  
  2. var server = http.createServer();  
  3.   
  4. server.on('request',function (req, res){  
  5.   res.writeHead(200, {'Content-Type': 'text/plain'});  
  6.   var name = require('url').parse(req.url,true).query.name  
  7.   res.end('Hello World ' + name);  
  8. });  
  9.   
  10. server.listen(1337, "127.0.0.1");  
  11.   
  12. console.log('Server running at http://127.0.0.1:1337/');  
将以上代码保存到  example3.js文件中,在cmd中敲入node example3.js

在浏览器地址栏中敲入  http://127.0.0.1:1337/hello?name=myname


挺简单的,下一节讲复杂的post http://www.linuxidc.com/Linux/2012-02/53535.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款