You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js 8.11.0调用POST接口时出现statuscode未定义错误求助

排查Node.js请求中"Cannot read property 'statuscode' of undefined"错误

首先看你遇到的错误,TypeError: Cannot read property 'statuscode' of undefined,这个问题的核心是你在回调里直接访问了response.statuscode,但此时response是undefined。这一般是因为请求过程中发生了错误,导致response没有被正常返回,而你的代码没有先处理错误情况。

接下来帮你拆解代码里的问题:

1. 未处理请求错误

在request.post的回调函数里,第一个参数是error,当请求失败(比如网络不通、URL错误、认证失败等)时,error会有值,而response会是undefined。你现在的代码直接跳过了错误判断,直接访问response的属性,这就会触发报错。

2. 属性名拼写错误

HTTP响应对象里的状态码属性是**statusCode(驼峰写法,C大写)**,而你写的是statuscode(全小写),就算请求成功,这个拼写错误也会让你拿到undefined。

3. 额外的检查点

  • 确认你的目标URLhttp://**.**.**.**/api/mid/sa/metrics是可访问的,没有防火墙或网络策略拦截
  • 确认用户名密码admin/event@1ert是正确的,认证能通过

修改后的代码

我把你的代码做了修正,加上了错误处理,修正了属性名拼写:

var request = require('request')
var fs = require('fs')
var now = +new Date()

function readContent(callback) {
  fs.readFile("C:\\powershell\\Config\\OIconfig.txt","utf8", function(error, config) {
    if (error) return callback(error)
    callback(null,config)
  })
}

readContent(function (err, config) {
  if (err) {
    console.error('读取配置文件失败:', err);
    return;
  }
  
  var userConfig = "admin";
  var passConfig = "event@1ert";
  var urlConfig = "http://**.**.**.**/api/mid/sa/metrics";
  
  console.log(passConfig)
  
  var options = {
    url: urlConfig,
    auth: {
      username: userConfig,
      password: passConfig
    },
    method: 'POST',
    json: [{
      'metric_type': 'CPU_Util',
      'resource': 'C:\\',
      'node': 'win-ces882ierw',
      'value': 10,
      'timestamp': now,
      'ci2metric_id': { 'node': 'win-ces882ierw' },
      'source': 'MetricOne'
    }]
  }

  request.post(options, function (error, response, body){
    // 首先处理错误情况
    if (error) {
      console.error('请求失败:', error);
      return;
    }
    
    // 现在可以安全访问response了,同时修正属性名
    console.log(response)
    console.log(response.statusCode) // 这里改成驼峰写法
    console.log(response.statusMessage)
    console.log(now)
    console.log(userConfig)
    console.log(passConfig)
    console.log(urlConfig)
  })
})

调试建议

运行修改后的代码后,如果还是报错,看控制台输出的错误信息,比如:

  • 如果是网络错误,说明目标地址不可达,需要检查网络和URL
  • 如果是认证错误,说明用户名密码有问题
  • 如果请求成功,就能正常打印状态码和响应内容了

内容的提问来源于stack exchange,提问作者Savi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:24:18