gpt4 book ai didi

javascript - Nodejs 代码执行中的 UnhandledPromiseRejectionWarning

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:33 24 4
gpt4 key购买 nike

我当前的nodejs版本是:8.9.1

我正在尝试执行我的代码,但总是遇到此错误,尝试修复它,但总是出现相同的错误:

(node:38) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'body' of undefined (node:38) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我的代码:

"use strict";
const rp = require("request-promise-native");
module.exports = async function (context) {
const stringBody = JSON.stringify(context.request.body);
const body = JSON.parse(stringBody);
const location = body.location;
if (!location) {
return {
status: 400,
body: {
text: "You must provide a location."
}
};
}
try {
const response = await rp(`https://query.yahooapis.com/v1/public/yql?q=select item.condition from weather.forecast where woeid in (select woeid from geo.places(1) where text="${location}") and u="c"&format=json`);
const condition = JSON.parse(response).query.results.channel.item.condition;
const text = condition.text;
const temperature = condition.temp;
return {
status: 200,
body: {
text: `It is ${temperature} celsius degrees in ${location} and ${text}`
},
headers: {
"Content-Type": "application/json"
}
};
} catch (e) {
console.error(e);
return {
status: 500,
body: e
};
}
}

我将非常感谢您的帮助。

谢谢。

最佳答案

内部错误告诉您,当您尝试检索 body 属性时,任何对象“body”的属性都未定义。在这种情况下,我的猜测是,当您尝试执行 JSON.stringify(context.request.body) 时,context.request 未定义。

您可以在此处阅读有关外部错误的更多信息 - https://nodejs.org/api/process.html#process_event_unhandledrejection

关于javascript - Nodejs 代码执行中的 UnhandledPromiseRejectionWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51636224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com