【问题标题】:How do I handle this TypeError: Cannot read property 'uri' of undefined如何处理此类型错误:无法读取未定义的属性“uri”
【发布时间】:2020-02-13 07:28:27
【问题描述】:

晚安,我在 const uri = ... 的第 8 行的代码中出现以下错误 第 8 行中声明的 uri const 似乎抛出错误,但我不知道它是什么。

(node:11524) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'uri' of undefined

我已包含以下代码。我们将不胜感激。

完整代码


class URIGenerator {
  getURI(controllerAction, params, id) {
    const caArray = controllerAction.split('_');
    const routeData = RoutesCollection[caArray[0]][caArray[1]];
    const uri = params ? this._bindParams(routeData.uri, params) : routeData.uri; //line 8
    return {
      id: id || routeData.action,
      method: routeData.method,
      uri,
    };
  }

  _bindParams(uri, params) {
    let match;
    let replacement;
    let uriParam = uri;
    const replacedParams = [];

    while (match = /:([\w_]+)\??/ig.exec(uriParam)) {
      replacement = params[match[1]].toString() || '';
      if (replacement === '') {
        uriParam = uriParam.replace(`/${match[0]}`, '');
      } else {
        uriParam = uriParam.replace(match[0], replacement);
        replacedParams.push(match[1]);
      }
    }

    const paramsForQueryString = {};
    Object.keys(params).forEach((p) => {
      if (!replacedParams.includes(p)) {
        paramsForQueryString[p] = params[p];
      }
    });

    if (Object.keys(paramsForQueryString).length > 0) {
      uriParam = `${uriParam}?${queryString.stringify(paramsForQueryString)}`;
    }

    return uriParam;
  }
}

module.exports = URIGenerator;

【问题讨论】:

  • 也许你给你的getURI方法提供了不正确的参数,尤其是controllerAction会话
  • 我会假设 routeData.uri 是错误。您应该检查您的 routeData 对象是否具有属性 uri。

标签: javascript node.js class express asynchronous


【解决方案1】:

错误码其实很清楚:

无法读取未定义的属性“uri”

您正在尝试访问两个地方的 .uri 属性,这两个地方都是“routeData.uri”。

您将其定义为:

const routeData = RoutesCollection[caArray[0]][caArray[1]];

所以可能 RoutesCollection 是代码中未包含的问题。

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2021-11-05
    • 2022-11-27
    相关资源
    最近更新 更多