NodeJS收发GET和POST请求

目录:

一 express框架接收

二 接收Get

三 发送Get

四 接收Post

五 发送Post

 

 

一 express框架接收

1 2 3 4 5 app. get ( ‘/‘ ,function(req,res) {      var  url = req.query.url;      var  name = req.query.name;      console.log(url, name); });

 

 

二 接收Get

1. get参数在req.url上

2. 使用url.parse将数据由字符串转变为obj

 

index.js:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 var  http = require( ‘http‘ ); var  url = require( ‘url‘ ); var  util = require( ‘util‘ );   //req 请求信息   res返回信息 http.createServer(function(req, res){      res.writeHeader(200, { ‘Content-Type‘ : ‘text/javascript;charset=UTF-8‘ });   //状态码+响应头属性        // 解析 url 参数      var  params  = url.parse(req.url,  true ).query;   //parse将字符串转成对象,req.url="/?url=123&name=321",true表示params是{url:"123",name:"321"},false表示params是url=123&name=321      res.write( "网站名:"  params .name);      res.write( "\n" );      res.write( "网站 URL:"  params .url);      res.end();   }).listen(3000);

 

浏览器打开:

1 http: //127.0.0.1:3000/?url=123&name=321

 

网页显示:

1 2 网站名:321 网站 URL:123

 

三 发送Get

index.js:

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 var  http = require( ‘http‘ );      var  qs = require( ‘querystring‘ );      var  data = {       a: 123,       time:  new  Date().getTime()}; //这是需要提交的数据          var  content = qs.stringify(data);      var  options = {       hostname:  ‘127.0.0.1‘      port: 10086,       path:  ‘/pay/pay_callback?‘  + content,       method:  ‘GET‘  };      var  req = http.request(options, function (res) {       console.log( ‘STATUS: ‘  + res.statusCode);       console.log( ‘HEADERS: ‘  + JSON.stringify(res.headers));       res.setEncoding( ‘utf8‘ );       res. on ( ‘data‘ , function (chunk) {           console.log( ‘BODY: ‘  + chunk);       });  });      req. on ( ‘error‘ , function (e) {       console.log( ‘problem with request: ‘  + e.message);  });      req.end();

  

 

四 接收Post

 当请求这个页面时,如果post数据中没有name和url,则返回一个提交页面;如果有name和url,则打印。

1. post请求会触发"data"事件。

2. chuck使用+=保存,因为会额外请求favicon.ico,导致body={}。

3. 请求结束,会触发"end"事件。将chuck反序列化querystring.parse(body)为对象数组, 使用body.name访问post变量。

 

index.js:

1  
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 var  http = require( ‘http‘ ); var  querystring = require( ‘querystring‘ );   var  postHTML =      ‘<html><head><meta charset="utf-8"><title>菜鸟教程 Node.js 实例</title></head>‘  +      ‘<body>‘  +      ‘<form method="post">‘  +      ‘网站名: <input name="name"><br>‘  +      ‘网站 URL: <input name="url"><br>‘  +      ‘<input type="submit">‘  +      ‘</form>‘  +      ‘</body></html>‘ ;   http.createServer(function (req, res) {      //暂存请求体信息      var  body =  "" ;        //请求链接      console.log(req.url);        //每当接收到请求体数据,累加到post中      req. on ( ‘data‘ , function (chunk) {          body += chunk;   //一定要使用+=,如果body=chunk,因为请求favicon.ico,body会等于{}          console.log( "chunk:" ,chunk);      });        //在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。      req. on ( ‘end‘ , function () {          // 解析参数          body = querystring.parse(body);   //将一个字符串反序列化为一个对象          console.log( "body:" ,body);          // 设置响应头部信息及编码\<br><br>      res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf8‘});
1 2 3 4 5 6 7 8 9 10          if (body.name && body.url) {  // 输出提交的数据              res.write( "网站名:"  + body.name);              res.write( "<br>" );              res.write( "网站 URL:"  + body.url);          else  {   // 输出表单              res.write(postHTML);          }          res.end();      }); }).listen(3000);

 

浏览器中打开:http://127.0.0.1:3000/

  

第一次访问127.0.0.1,post中没有name和url,显示提交页面。

点击提交后,网页会打印出如下结果。

问题:

1. req.on("end"事件会多次触发。因为会请求favicon.ico。

 

2.  res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf8‘}); 

text/html的意思是将文件的content-type设置为text/html的形式,浏览器在获取到这种文件时会自动调用html的解析器对文件进行相应的处理。

text/plain的意思是将文件设置为纯文本的形式,浏览器在获取到这种文件时并不会对其进行处理。

 

五 发送Post

index.js:

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 var  http = require( ‘http‘ ); var  querystring = require( ‘querystring‘ );   var  contents = querystring.stringify({      name: ‘byvoid‘ ,      email: ‘byvoid@byvoid.com‘ ,      address: ‘Zijing‘ });   var  options = {      host: ‘www.byvoid.com‘ ,      path: ‘/application/node/post.php‘ ,      method: ‘POST‘ ,      headers:{          ‘Content-Type‘ : ‘application/x-www-form-urlencoded‘ ,          ‘Content-Length‘ :contents.length      } }   var  req = http.request(options, function(res){      res.setEncoding( ‘utf8‘ );      res. on ( ‘data‘ ,function(data){          console.log( "data:" ,data);    //一段html代码      }); });   req.write(contents); req.end;

  

 

相关文章