var API_KEY= 'XXX';
CHANNEL_ID = 'XXX';
router.get('/', function(req, res) {
request.get('https://www.googleapis.com/youtube/v3/search', { part: 'snippet', channelId: CHANNEL_ID, type: 'video', eventType: 'live', key: API_KEY }, function(data) {
try {
if(data['items'].length > 0)
res.json({status: true});
}
catch (err) {
res.json({status: false});
console.log(err)
}
});
});
TypeError: Cannot read property 'length' of undefined
at Request._callback (C:\Users\Steve\Desktop\Own api check\server.js:24:21)
at self.callback (C:\Users\Steve\Desktop\Own api check\node_modules\request\request.js:185:22)
at Request.emit (events.js:182:13)
at Request.start (C:\Users\Steve\Desktop\Own api check\node_modules\request\request.js:749:10)
at Request.end (C:\Users\Steve\Desktop\Own api check\node_modules\request\request.js:1506:10)
at end (C:\Users\Steve\Desktop\Own api check\node_modules\request\request.js:560:14)
at Immediate._onImmediate (C:\Users\Steve\Desktop\Own api check\node_modules\request\request.js:574:7)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)
完整代码:
我正在尝试创建一个API,该API可以读取和写入YouTube数据 在我的网站上对我来说,如果那个人在心中, 总是给我这样的错误
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var request = require('request');
//Configure app to use bodyParser();
app.use(bodyParser.urlencoded({ extend: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 1337;
//Routes for the API
var router = express.Router();
router.use(function(req, res, next) {
console.log("Got Request"); // -> Something is happening
next();
})
var API_KEY= '';
CHANNEL_ID = 'UCmDM6zuSTROOnZnjlt2RJGQ';
router.get('/', function(req, res) {
request.get('https://www.googleapis.com/youtube/v3/search', { part: 'snippet', channelId: CHANNEL_ID, type: 'video', eventType: 'live', key: API_KEY }, function(data) {
try {
if(data['items'].length > 0)
res.json({status: true});
}
catch (err) {
res.json({status: false});
console.log(err)
}
});
});
//Custom URL e.g. example.com:1337/api/ECHO
router.route('/:echo').get(function(req, res) {
res.json({echo: req.params.echo});
})
//All routes will be prefixed with /api
app.use('/api', router);
//Start the server
app.listen(port);
console.log('API server has been started on port ' + port);
答案 0 :(得分:0)
错误在此行
if(data['items'].length > 0)
数据对象没有'items'属性。对数据对象执行console.log以查看返回了什么。似乎未正确调用Youtube API,而是返回了错误。
请在您的请求中尝试以下代码:
request({url: "https://www.googleapis.com/youtube/v3/search?",
qs:{
part: 'snippet',
channelId: CHANNEL_ID,
type: 'video',
eventType: 'live',
key: API_KEY
}
}, function(err, response, data){
if (err){
console.log(err);
}
console.log(data);
if(data['items'].length > 0) {
res.json({status: true});
}
});