nodejs很方便的就是引入各种各样的包,但是要区分同样的请求,不一样的操作。
今天给大家介绍,我在工作中遇到3天的一个bug,连续发送post 请求得不到响应 ,底层不报错。
不同的三种方式发送:
1、 let http = require('http');
http.request 请求 ,相信大家都用过。
for(let i =0;i<10;i++){
let http = require('http');
let post_data =JSON.stringify({
'txid':Math.random().toString(32).slice(2),
'dataHash':Math.random().toString(32).slice(2),
'data':Math.random().toString(32).slice(2),
'publicKey':Math.random().toString(32).slice(2),
'signature':Math.random().toString(32).slice(2),
'remark':'',
'appId':Math.random().toString(32).slice(2)
});
console.log(post_data);
let options = {
hostname:'10.10.144.30',//此处不能写协议,如 : http://,https:// 否则会报错
port:7451,
path:'/UChains/poe/poe/transaction',
method:'POST',
headers: {
'Content-Type':'application/x-www-form-urlencoded',
'Content-Length':Buffer.byteLength(post_data)
}
};
console.log('________Send__________');
let req =http.request(options,function(res){
console.log('________success_________');
console.log('STATUS:'+res.statusCode);
console.log('HEADERS:'+JSON.stringify(res.headers));
res.on('data',function(chunk){
console.log('BODY:'+chunk);
});
});
req.write(post_data);
req.end();
}
2、const request = require('request-promise');
for(let i = 0;i<10;i++) {
const request = require('request-promise');
let zsh = {
'txid': 'AJECb3aQseQ7idRcFpGiPEBpki8Ec2cY',
'dataHash': '4iKD7mJsHJBB7r2d48hr8mk86rmzsnHE',
'data': 'yW3fSi3nCTmS6sEstafeSSNMmRRxZMNX',
'publicKey': 'tDrcktHMM4zD6FPbsyPRxfccNaH5BHMJ',
'signature': 'fnv624629k8',
'remark': '',
};
let url ='http://10.10.144.30:7451/UChains/poe/poe/transaction';
//uri: 'http://192.168.56.101:7451/UChains/poe/poe/transaction;
console.log(zsh);
let options = {
uri: url,
method: 'POST',
json: zsh
};
request(options, function (err, response, body) {
if (!err && response.statusCode === 200) {
console.log(response.statusCode, body);
return Promise.resolve(body);
} else {
console.log('Send Post postContract, ' + (err.stack ? err.stack : err));
return Promise.reject(err);
}
});
* 3、let request = require('sync-request');
let zsh = {
'txid': 'AJECb3aQseQ7idRcFpGiPEBpki8Ec2cY',
'dataHash': '4iKD7mJsHJBB7r2d48hr8mk86rmzsnHE',
'data': 'yW3fSi3nCTmS6sEstafeSSNMmRRxZMNX',
'publicKey': 'tDrcktHMM4zD6FPbsyPRxfccNaH5BHMJ',
'signature': 'fnv624629k8',
'remark': '',
};
let request = require('sync-request');
for(let i=0;i<10;i++){
let res = request('POST', 'http://10.10.144.30:7451/UChains/poe/poe/transaction', {
json:zsh
});
console.log(zsh);
console.log(JSON.parse(res.getBody('utf8')));
}
测试之后发现 应用sync-request 实现同步操作
大家可以测试使用,function + async + wait settimeout 使用 是否能实现同步情况 、