TypeError:无法读取未定义的属性“ DASH”

时间:2019-05-11 20:36:02

标签: node.js angular api express

在我当前的项目中,我想显示一些数据(加密统计)。通过调用API,我得到了有效的响应。

我的环境是:

节点:8.9.5, 快递:4.16.4, Angular CLI:7.3.6, 打字稿:3.2.4, 操作系统:darwin x64

这是我的代码:

const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const cors = require('cors')

// Create an express app
const app = express()

// Error-fix: Cross-Origin
app.use(cors())

ticker = "DASH";

// Define a default route handler for the Node app
app.get('/getDetails', (req, res) => {
    let options = {
        'url': 'https://api-call-something.io/',
        'formData': {"access-token": "xxxxx-xxxxx-xxxxx", "ticker": ticker},
        'method': "POST"
    }; 

    request(options).pipe(res);
})

这是我的回复:

响应:

{
    "success": true,
    "message": {
        "DASH": {
            "semantic_version": "0.12.3.3",
            "last_block": 982197,
            "block_age": 446554,
            "statuses": {
                "ENABLED": 4898,
                "SENTINEL_PING_EXPIRED": 11,
                "NEW_START_REQUIRED": 46,
                "UPDATE_REQUIRED": 60,
                "PRE_ENABLED": 1,
                "POSE_BAN": 1
            },
            "usd_price": 111.50325810328,
            "btc_price": "0.02107716",
            "change_24h": -2.42056,
            "roi": 6.77475551,
            "collateral": 1000,
            "payout_sum_daily": "909.11649250",
            "payout_count_daily": 543,
            "payout_period": 779350.464,
            "daily_income": {
                "coin": 0.1856,
                "btc": "0.00391213",
                "usd": 20.6961
            }
        }
    }
}

当我尝试访问usd_price值时出现错误:

app.get('/getDetails', (req, res) => {
    let options = {
        'url': 'https://api-call-something.io/',
        'formData': {"access-token": "xxxxx-xxxxx-xxxxx", "ticker": ticker},
        'method': "POST"
    };

    request(options).pipe(res);

    usd = res.message['DASH'].usd_price;

    console.log(usd);
    console.log(res);
})
TypeError: Cannot read property 'DASH' of undefined

3 个答案:

答案 0 :(得分:0)

使用此方法:

    let message = res['message'];
    let dash = Object.keys(message)[0];
    let jsonObject: any = message[dash];
    console.log("USD Price: " + jsonObject['usd_price']);

答案 1 :(得分:0)

您的意思是pipe res进入请求吗?您要这样做是什么?

pipe用于文件上传或向api发送原始数据之类的事情,因为您已经发送了formData,我认为您不需要这些。

尝试将代码更改为此:

app.get('/getDetails', (req, res) => {
    let options = {
        'url': 'https://api-call-something.io/',
        'formData': {"access-token": "xxxxx-xxxxx-xxxxx", "ticker": ticker},
        'method': "POST"
    };

    // Call request and handle response in callback
    request(options, (err, response, body) => {
      if (err || response.statusCode !== 200) {
        console.log(err);
        res.status(response.statusCode).send(err.message);
        return
      }
      const usd = body.message.DASH.usd_price;

      console.log(usd);

      // Send whatever response you want
      res.send(usd)
    })
})

答案 2 :(得分:0)

我不确定您是否看到代码没有在全局范围内声明为变量。调用它肯定会返回未定义。 与usd声明相同。您无法将未声明的变量记录到控制台,该变量肯定会返回undefined。

为您重构的代码:

const bodyParser = require("body-parser");
const request = require("request");
const cors = require("cors");

// Create an express app
const app = express();

// Error-fix: Cross-Origin
app.use(cors());

const ticker = "DASH";

// Define a default route handler for the Node app
app.get("/getDetails", (req, res) => {
  let options = {
    url: "https://api-call-something.io/",
    formData: { "access-token": "xxxxx-xxxxx-xxxxx", ticker: ticker },
    method: "POST"
  };

  request(options).pipe(res);

  const usd = res.message.DASH.usd_price;

  console.log(usd);
  console.log(res);
});