nodejs http 发送到php,nodejs作为客户端发送请求

nodejs不只是可以作为服务端响应客户端的请求,还可以作为客户端向其他服务端发送请求。例如一些第三方敏感数据的操作,就可以用nodejs作为中转。

nodejs内置http/https模块,一方面用于搭建服务,另外也提供了作为客户端请求的方法,注意:访问http服务用http模块,方位https服务用https模块,接下来以http作为演示:

http.get()

var http=require("http");

http.get("http://py.amazingtm.com/index.php?keyword=veblen&keytype=0",function(data){

var str="";

data.on("data",function(chunk){

str+=chunk;//监听数据响应,拼接数据片段

})

data.on("end",function(){

console.log(str.toString())

})

})

有同学觉得,拼接参数的方式不够优雅,那么可以使用 querystring模块的stringify方法进行转换,下面会有演示。

http.request() --get

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();

http.request() --post

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 = {

hostname: '127.0.0.1',

port: 10086,

path: '/pay/pay_callback',

method: 'POST',

headers: {

'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'

}

};

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.write(content);//注意这个地方

req.end();

会发现,略微有些繁琐,nodejs中有一个第三方模块request可以一试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值