[英]Getting 'TypeError: Cannot read property '0' of undefined' when attempting to get a piece of data from MediaWiki API
I'm attempting to code something to get various attributes from the MediaWiki API.我正在尝试编写一些代码以从 MediaWiki API 获取各种属性。 However, it throws an error when I attempt to get certain data from the page, for example, the title.
但是,当我尝试从页面获取某些数据(例如标题)时,它会引发错误。
const reqDesc = (requestid) => new Promise((resolve, reject) => {
request({
method: 'GET',
url: `https://example.wikia.com/api/v1/Articles/AsSimpleJson?id=${requestid}`
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
return resolve(`<${body.sections[0].content[0].text}>`);
} else if (error) {
return reject(`Error: ${error}`);
} else {
return reject(`Response code: ${response.statusCode}`);
}
});
});
(I know request is deprecated, I'm attempting to find something better.) (我知道 request 已被弃用,我正在尝试找到更好的东西。)
The above code should work, however at return resolve(`<${body.items[0].id}>`);
上面的代码应该可以工作,但是在
return resolve(`<${body.items[0].id}>`);
, it throws 'TypeError: Cannot read property '0' of undefined' ,它抛出'TypeError:无法读取未定义的属性'0''
Instead of request
, you could use Axios .代替
request
,您可以使用Axios 。 As for 'TypeError: Cannot read property '0' of undefined'
, it means either sections
or content
is undefined.至于
'TypeError: Cannot read property '0' of undefined'
,表示sections
或content
未定义。 You might want to take a look at what is inside body
.你可能想看看
body
里面是什么。
Example:例子:
let requestid = 1;
let url = `https://example.wikia.com/api/v1/Articles/AsSimpleJson?id=${requestid}`;
axios({
url: url,
responseType: 'json',
})
.then(response => {
console.log('--response--');
let section = reponse.data.sections[0] || {};
let content = section.content || {};
let elem = content[0] || {};
let text = content.text;
return text;
})
.then(console.log)
.catch(error => {
console.log('--error--');
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.