nodejs的http.request使用post方式提交資料請求
阿新 • • 發佈:2019-01-09
https://www.cnblogs.com/sunwubin/archive/2013/11/09/3416246.html
直接上程式碼: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)提交資料,關鍵是下面兩點:
- 使用 querystring.stringify 對資料進行序列化
- 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);
});
|