js:TypeError:无法使用读取未定义的属性“ replace”

时间:2020-10-30 06:55:31

标签: javascript node.js reactjs webpack

我想用空字符串替换/\r?\n|\r/g,但出现类型错误“无法读取未定义的属性'replace'”。

export function getCupsCredentials() {
    var vcap_services = process.env.VCAP_SERVICES;
    var vcap_servces_as_single_line = vcap_services.replace(/\r?\n|\r/g, " ");
    var vcap_servces_as_json = JSON.parse(vcap_servces_as_single_line)
    var vcap_servces_user_provided = vcap_servces_as_json['user-provided']
    var cups_credentials = vcap_servces_user_provided[0].credentials;
    return cups_credentials;
}

我在使用.replace时收到以下错误消息

TypeError: Cannot read property 'replace' of undefined
at getCupsCredentials (/app/ui/dist/webpack:/src/utils/VcapUtils.js:4:50)
at Object.defineProperty.value (/app/ui/dist/webpack:/src/utils/IAMUtils.js:5:17)
at __webpack_require__ (/app/ui/dist/webpack:/webpack/bootstrap 713b700ece87295bcf31:19:1)
at Object.defineProperty.value (/app/ui/dist/webpack:/src/api/middleware/filters/authFilter.js:1:1)
at __webpack_require__ (/app/ui/dist/webpack:/webpack/bootstrap 713b700ece87295bcf31:19:1)
at Object.<anonymous> (/app/ui/dist/webpack:/src/api/middleware/pre.js:1:1)
at __webpack_require__ (/app/ui/dist/webpack:/webpack/bootstrap 713b700ece87295bcf31:19:1)
at Object.defineProperty.value (/app/ui/dist/webpack:/src/api/middleware/index.js:1:1)
at __webpack_require__ (/app/ui/dist/webpack:/webpack/bootstrap 713b700ece87295bcf31:19:1)
at Object.canUseDOM (/app/ui/dist/webpack:/src/server.js:4:1)
Starting Conductor UI
using Conductor API server from 'http://chand-wf-nfce-server.cloud.pcftest.com/api'
 
/app/ui/dist/webpack:/src/utils/VcapUtils.js:4
var vcap_servces_as_single_line = vcap_services.replace(/\r?\n|\r/g, " ");

2 个答案:

答案 0 :(得分:1)

如果要从远程服务器获取这些值,则可能是您在将数据分配给变量之前尝试替换字符。尝试使用await函数或.then(),并替换为var vcap_servces_as_single_line = vcap_services?.replace(/\r?\n|\r/g, " ");

因此,如果您具有未定义的值,则代码不会对您大喊大叫。

答案 1 :(得分:1)

最可能的原因是您的process.env.VCAP_SERVICES未正确初始化,并且正在用vcap_services初始化undefined。由于replace方法不适用于undefined,因此会出现该错误。

尝试由三元运算符检查vcap_services是否为空

export function getCupsCredentials() {
  var vcap_services = process.env.VCAP_SERVICES;
  var vcap_servces_as_single_line = vcap_services
    ? vcap_services.replace(/\r?\n|\r/g, " ")
    : "vcap_servisec is empty";
  console.log(vcap_services);
  /*
    var vcap_servces_as_json = JSON.parse(vcap_servces_as_single_line)
    var vcap_servces_user_provided = vcap_servces_as_json['user-provided']
    var cups_credentials = vcap_servces_user_provided[0].credentials;
    return cups_credentials;
    */
}