【发布时间】:2020-06-23 19:06:04
【问题描述】:
我正在运行一个 webhook 以从 Seller.tools api 中提取和处理数据。
我正在尝试使用 node-fetch 调用他们的 api。当我在 cloud9 ide 中对其进行测试时,将其传输到 aws-lambda,无论如何我尝试获取它作为未定义的结果。
事实上,如果我尝试在.then 中调用console.log,它甚至都不会出现。此外,除非我尝试进一步访问结果,否则它甚至不会引发错误。
...
var order, status;
let url='https://data.seller.tools/api/v1/orders/'+orderid;
let options={
headers:{
'Authorization':apikey
}
};
try{
fetch(url,options)
.then(res => {status=res.status;order=res.json();return res;})
.then(res => console.log(res))
.catch(err => console.error("Err"+err));
}catch(err){console.log(err)}
console.log("order: "+order);
console.log("status: "+status);
console.log(order.order_id);
...
结果:
order: undefined
status: undefined
{"errorType":"TypeError","errorMessage":"Cannot read property 'order_id' of undefined"}
我在 talend api tester 扩展中使用了相同的 url 和标题,它可以正常工作。但在我的代码中,在 cloud9 ide 中运行测试,它没有。 怎么回事?
【问题讨论】:
-
我猜是授权密钥的格式。请注意,3xx-5xx 响应不是例外,因此您很可能会得到一些东西,但由于授权失败而没有响应。在 node-fetch npm 站点上,有一组关于如何检查状态错误的说明。 “处理客户端和服务器错误” - 试试看。并且所有最后一个 console.log 语句都将是未定义的,因为您正在进行异步调用。您将在 fetch 返回任何内容之前点击 console.log 语句。
-
那么如何让我的脚本在继续之前等待响应?
-
欢迎来到异步 Javascript 的世界!在异步函数中等待结果,或者您需要开始链接承诺调用。 status 和 statusText 是什么?
-
我在想我正在通过
.then链接承诺调用。我需要此函数同步工作,以便我可以继续执行脚本。一切都取决于此获取。
标签: node.js aws-lambda aws-cloud9 node-fetch