官方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
|
<?phpecho 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);
}); |