我在nodejs中执行http请求,但是该请求永无止境,并继续执行以下代码。它只打印出“响应结束”,而不打印出“请求结束”。为什么会这样呢?
const post_data = JSON.stringify({
'username': username,
'org': orgName,
'peers': peers,
'channelName': channelName,
'chaincodeName': chaincodeName,
'fcn': fcn,
'args': args
});
var post_options = {
host: 'localhost',
port: '3000',
path: '/cc/write',
method: 'POST',
headers: {
"content-type": "application/json",
"Content-Length": Buffer.byteLength(post_data)
}
};
var post_req = http.request(post_options, function (res) {
console.log("connected");
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
ccResponse = chunk;
});
res.on('end', function () {
console.log('response end')
});
});
// post the data
post_req.write(post_data);
post_req.on('end', function () {
console.log('request end');
});
post_req.on('finish', function () {
console.log('request end');
});
post_req.end();
console.log("Random thing");
答案 0 :(得分:0)
最后一行console.log("Random thing");
上方有一个额外的括号
除去该括号后,代码生成了以下日志:
Random thing
request end
connected
Response: {"error":"Not Found"}
response end
您可以看到日志中有“请求结束”。 它与节点v11.13.0一起运行。
如果没有帮助,请通知我。
我使用的实际代码:
const http = require('http');
const post_data = JSON.stringify({
'username': 'username',
'org': 'orgName',
'peers': 'peers',
'channelName': 'channelName',
'chaincodeName': 'chaincodeName',
'fcn': 'fcn',
'args': 'args'
});
var post_options = {
host: 'localhost',
port: '3000',
path: '/cc/write',
method: 'POST',
headers: {
"content-type": "application/json",
"Content-Length": Buffer.byteLength(post_data)
}
};
var post_req = http.request(post_options, function (res) {
console.log("connected");
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
ccResponse = chunk;
});
res.on('end', function () {
console.log('response end')
});
});
// post the data
post_req.write(post_data);
post_req.on('end', function () {
console.log('request end');
});
post_req.on('finish', function () {
console.log('request end');
});
post_req.end();
console.log("Random thing");