node 提交post请求带参数

2014-09-18  文晶 

var http = require('http');

 var querystring = require('querystring');

 var params =querystring.stringify({
        "requestId":requestId,
        "amount":amount
    });

var options = {

        hostname: 'xxxx',
        port:xxxx,
        path:'/xxxxx/xx/xxx',
        method: 'post',
        headers: {
            'Content-Type':"application/x-www-form-urlencoded",
            "Content-Length": params.length
        }
    }

//链接服务器
    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 (body) {
            console.log('BODY: ' + body);
        });

    });




    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });
//传递参数
   req.write(params);

   res.json(data);












// pay.js


var http = require('http');
function epay(params)
{


console.log(" COME IN"); 
var params = JSON.stringify({ 
"sign":"ExdYcut6LgrKGsHuAyoxFTMDuDYVmyFFu7GRHPRwB/DBwm6cyBe9Sr2rti1/SjWPcdXLoWIHWEJ9IFKPK+3ieKU/MkNqeh1opH/4MEM59W314jQL3/sPS+X8qsEInj7OsfXCfOKXJXTw+WeVBOBHep4SBIAkgLjvRYSg1/Bv7ck="
});


var options = { 
host: '127.0.0.1', 
port: 80,
path: '/index/',
method: 'post',
headers: {
'Content-Type':'application/x-www-form-urlencoded',
'Content-Length':params.length
}};






//使用http 发送
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));




//设置字符编码
res.setEncoding('utf8');


//返回数据流
var _data="";


//数据
res.on('data', function (chunk) {
_data+=chunk;
console.log('BODY: ' + chunk);
});


// 结束回调
res.on('end', function(){
console.log("REBOAK:",_data)
});


//错误回调 // 这个必须有。 不然会有不少 麻烦
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});






});


req.write(params + "\n");
req.end();


}
exports.epay=epay;








// index.js 主入口
var epay = require('./epay');
console.log('STERT EPAYING ');
epay.epay("");






cmd进入node 命令。
>node index.js

500°/5003 人阅读/0 条评论 发表评论

登录 后发表评论