Page 83 - Node.js开发指南
P. 83

4.5  HTTP 服务器与客户端    75


                   下面是一个通过 http.request 发送 POST 请求的代码:                                                1

                   //httprequest.js

                   var http = require('http');
                   var querystring = require('querystring');                                          2

                   var contents = querystring.stringify({
                     name: 'byvoid',
                     email: 'byvoid@byvoid.com',
                     address: 'Zijing 2#, Tsinghua University',
                   });                                                                                3

                   var options = {
                     host: 'www.byvoid.com',
                     path: '/application/node/post.php',
                                                                                                      4
                     method: 'POST',
                     headers: {
                       'Content-Type': 'application/x-www-form-urlencoded',
                       'Content-Length' : contents.length
                     }
                   };                                                                                 5

                   var req = http.request(options, function(res) {
                     res.setEncoding('utf8');
                     res.on('data', function (data) {
                       console.log(data);                                                             6
                     });
                   });

                   req.write(contents);
                   req.end();
                                                                                                      7
               运行后结果如下:

                   array(3) {
                     ["name"]=>
                     string(6) "byvoid"                                                               8
                     ["email"]=>
                     string(17) "byvoid@byvoid.com"
                     ["address"]=>
                     string(30) "Zijing 2#, Tsinghua University"
                                                                                                      9
                   }

                              不要忘了通过 req.end() 结束请求,否则服务器将不会收到信息。

                                                                                                      10
   78   79   80   81   82   83   84   85   86   87   88