抱歉,如果格式不正确。我目前正在使用Express路由器使用axios向第三方api发出请求。我正在尝试使用transformResponse修改响应对象,以便更好地使用结果。问题是当这样调用时,节点会以“ typeError:无法将未定义或null转换为对象”作为响应
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
router.get('/', (req, res) => {
axios.get(`${stockURL}?symbol=googl`, {
params: {
function: 'TIME_SERIES_DAILY',
apikey: ALPHA_KEY,
outputsize: 'full'
},
transformResponse: [function (data) {
// Do whatever you want to transform the data
function fixKeys(obj) {
Object.keys(obj).forEach(function (key) {
let newKey = key.split('.')[1].trim();
//dynamic form of obj.newKey
obj[newKey] = obj[key];
delete obj[key];
});
return obj;
}
//the main object with all dates by day
// let fullData = data[stockDay.json];
let fullData = data['Time Series (Daily)'];
let arrayData = [];
// adds a key value pair for the date, with the date of the stock quote,
//and then deletes the key 'Time Series (Daily)'
Object.keys(fullData).map(function (key) {
let obj = {};
obj = fixKeys(fullData[key]);
obj['date'] = key;
arrayData.push(obj);
});
//current days data
todayData = arrayData[0];
//get 52 week high/low
let arrayLow = [];
let arrayHigh = [];
for (let i = 0; i < 365 && i < arrayData.length; i++) {
arrayLow.push(parseInt(arrayData[i].low));
arrayHigh.push(parseInt(arrayData[i].high));
}
todayData['tlow'] = Math.min.apply(null, arrayLow);
todayData['thigh'] = Math.max.apply(null, arrayLow);
return todayData;
}]
})
.then((payload) => {
console.log(payload.todayData)
res.json(payload.todayData);
})
.catch((err) => {
console.error(err);
res.status(500).json({
message: 'Something went wrong while querying Alphavantage'
})
})
});