nodejs的http.request使用post方式提交數據請求


官方api文檔 http://nodejs.org/docs/v0.6.1/api/http.html#http.request雖然也有POST例子,但是並不完整。

直接上代碼:http_post.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
33
34
var http=require( 'http' );
var qs=require( 'querystring' );
 
var post_data={a:123,time: new Date().getTime()}; //這是需要提交的數據
var content=qs.stringify(post_data);
 
var options = {
   host: '127.0.0.1' ,
   port: 80,
   path: '/post.php' ,
   method: 'POST' ,
   headers:{
   'Content-Type' : 'application/x-www-form-urlencoded' ,
   'Content-Length' :content.length
   }
};
console.log( "post options:\n" ,options);
console.log( "content:" ,content);
console.log( "\n" );
 
var req = http.request(options, function (res) {
   console.log( "statusCode: " , res.statusCode);
   console.log( "headers: " , res.headers);
   var _data= '' ;
   res.on( 'data' , function (chunk){
      _data += chunk;
   });
   res.on( 'end' , function (){
      console.log( "\n--->>\nresult:" ,_data)
    });
});
 
req.write(content);
req.end();

 

接受端地址為:http://127.0.0.1/post.php

1
2
<?php
echo json_encode( $_POST );

 

要正確的使用nodejs模擬瀏覽器(nodejs httpClient)提交數據,關鍵是下面兩點:

  1. 使用 querystring.stringify 對數據進行序列化
  2. request的 options中添加相應headers信息:Content-Type和Content-Length

https的request和http的request是一樣的,所以只需要將require('http')修改為require('https') 既可以進行https post提交了。

 

這個是我寫的一個進行POST的函數,支持http和https:

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
function post(url,data,fn){
       data=data||{};
       var content=require( 'querystring' ).stringify(data);
       var parse_u=require( 'url' ).parse(url, true );
       var isHttp=parse_u.protocol== 'http:' ;
       var options={
            host:parse_u.hostname,
            port:parse_u.port||(isHttp?80:443),
            path:parse_u.path,
            method: 'POST' ,
            headers:{
                   'Content-Type' : 'application/x-www-form-urlencoded' ,
                   'Content-Length' :content.length
             }
         };
         var req = require(isHttp? 'http' : 'https' ).request(options, function (res){
           var _data= '' ;
           res.on( 'data' , function (chunk){
              _data += chunk;
           });
           res.on( 'end' , function (){
                 fn!=undefined && fn(_data);
            });
         });
         req.write(content);
         req.end();
}

如下使用

1.http方式:

1
2
3
post( 'http://127.0.0.1/post.php?b=2' ,{a:1}, function (data){
   console.log(data);
});

2.https方式:

1
2
3
post( 'https://127.0.0.1/post.php' ,{a:1}, function (data){
   console.log(data);
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM