为什么 node.js module.export 没有全局返回?



下面是我的代码,它是一个GET请求,它将返回一个票号(我省略了标题/选项/身份验证(。

我想知道为什么下面的第一个控制台.log返回票证号(应该返回(,但第二个控制台日志不返回票号。

我需要导出票号以触发另一个模块。 有没有办法在这个区域之外获得那个票号? 我被难住了。

提前谢谢。

options.path += orderNumber;
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
global.body = Buffer.concat(chunks);
module.exports.cw = JSON.parse(body.toString()).customerOrderNo.replace(/D/g,'');
**console.log(module.exports.cw);**
});  
});
**console.log(module.exports.cw);**
req.write(JSON.stringify({ id: 0,
description: 'maxLength = 100',
url: 'Sample string',
objectId: 0,
type: 'Sample string',
level: 'Sample string',
memberId: 0,
inactiveFlag: 'false' }));
req.end();

您可以将第一个console.log(module.exports.cw);更改为console.log(1, module.exports.cw);,将console.log(module.exports.cw);更改为console.log(2, module.exports.cw);

您的主机将记录:

2, undefined
1, <something>

当你调用https.request时,它请求url和获取数据,需要时间来结束它(res.on("end", <this callback>)的调用函数(

当您请求时,Node.jshttp.request之后的呼叫线路:console.log(module.exports.cw);,但现在在内部回拨https.request没有呼叫(需要时间来请求和呼叫(,因此module.exports.cwundefined

您应该更改req.write以回拨https.request

我认为这是范围界定的问题。看看下面的代码,我们将导出移到模块的底部。

options.path += orderNumber;
var ticketNumber;
var req = https.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
global.body = Buffer.concat(chunks);
ticketNumber = JSON.parse(body.toString()).customerOrderNo.replace(/D/g,'');
**console.log(ticketNumber);**
});  
});
**console.log(ticketNumber);**
req.write(JSON.stringify({ id: 0,
description: 'maxLength = 100',
url: 'Sample string',
objectId: 0,
type: 'Sample string',
level: 'Sample string',
memberId: 0,
inactiveFlag: 'false' }));
req.end();
module.exports.getCw = function(){return ticketNumber}

最新更新