I'm trying to parse so I can check if the username is valid or not. Though I have little to no experience working with JSON parasing in NodeJS. I'd appreciate some help on this issue. This has been a struggle moving over to NodeJS and trying to work with APIs and parasing them.
Here's the code and here is the error
userid = body[0]['data']['user']['id'];
^
TypeError: Cannot read properties of undefined (reading 'data')
at Request._callback (C:\Users\Tommy\Desktop\Misc\Node Projects\Discord Twitch Username Check\index.js:141:25)
at Request.self.callback (C:\Users\Tommy\Desktop\Misc\Node Projects\Discord Twitch Username Check\node_modules\request\request.js:185:22)
at Request.emit (node:events:390:28)
at Request.<anonymous> (C:\Users\Tommy\Desktop\Misc\Node Projects\Discord Twitch Username Check\node_modules\request\request.js:1154:10)
at Request.emit (node:events:390:28)
at IncomingMessage.<anonymous> (C:\Users\Tommy\Desktop\Misc\Node Projects\Discord Twitch Username Check\node_modules\request\request.js:1076:12)
at Object.onceWrapper (node:events:509:28)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
function getUser(username) {
const opts = {
"url": `https://gql.twitch.tv/gql`,
headers: {
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
'Accept-Language': 'en-US',
'sec-ch-ua-mobile': '?0',
'Client-Version': '7b9843d8-1916-4c86-aeb3-7850e2896464',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
'Content-Type': 'text/plain;charset=UTF-8',
'Client-Session-Id': '51789c1a5bf92c65',
'Client-Id': 'kimne78kx3ncx6brgo4mv6wki5h1ko',
'X-Device-Id': 'xH9DusxeZ5JEV7wvmL8ODHLkDcg08Hgr',
'sec-ch-ua-platform': '"Windows"',
'Accept': '*/*',
'Origin': 'https://www.twitch.tv',
'Sec-Fetch-Site': 'same-site',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
'Referer': 'https://www.twitch.tv/',
},
body: '[{"operationName": "WatchTrackQuery","variables": {"channelLogin": "'+username+'","videoID": null,"hasVideoID": false},"extensions": {"persistedQuery": {"version": 1,"sha256Hash": "38bbbbd9ae2e0150f335e208b05cf09978e542b464a78c2d4952673cd02ea42b"}}}]'
}
request(opts, (err, res, body) => {
body = JSON.parse(body);
userid = body[0]['data']['user']['id'];
if(userid === 0){
return "Invalid Username"
}else{
return userid;
}
});
};