javascript - Nodejs 代码执行中的 UnhandledPromiseRejectionWarning

标签 javascript node.js

我当前的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/

相关文章:

javascript - node.js 监控何时创建文件

javascript - native Javascript 警报 - 样式覆盖删除新行功能

javascript - 如何在Vuejs中使用数组在父组件和子组件之间应用监视

node.js - Mongoose/Node 如何直接在EJS文件中访问数据库

node.js - 如何获取过去 7 天的所有记录 sequelize

javascript - npm 错误!代码 E401 npm 错误!密码错误或丢失

javascript - Node.js 使用模块中的变量

node.js - 为什么 Gatsby 不再识别站点目录中的组件?

javascript - 在快速响应中获取空数组

python websocket 客户端连接状态 - 如何更新以便获得正确的状态?