Hello everyone! I need to send http get request to twitch API. How it works: User inputs name of the streamer, my programm sends http get request to twitch API and the output need to be how much viewers right now on the twitch stream. my try:
import fetch from 'node-fetch';
const response = await fetch('https://www.google.com/');
const data = await response.json();
console.log(data);
CodePudding user response:
I recommend that you use a package like axios
to make your request. That is because to authenticate you need to send a POST requeust
as well which axios makes very easy.
First you need to authenticate to the server this can be done like so
axios.post('https://id.twitch.tv/oauth2/token', {
client_id: '<your client id>',
client_secret: '<your client id>',
grant_type: 'client_credentials'
})
.then(function (response) {
console.log(response);
// the response will look like this
// save the access token you will need it for every request you send
/*
{
"access_token": "jostpf5q0puzmxmkba9iyug38kjtg",
"expires_in": 5011271,
"token_type": "bearer"
}
*/
})
You can query for a channel like this. You can find all request you can make and their response here. Again here you need to provide the authentication from the previous step
axios.get('https://api.twitch.tv/helix/search/channels?query=loserfruit', {
headers: {
'Client-Id': '<your client id>',
'Authorization': 'Bearer <access_token fron previous request>'
}})
.then(function (response) {
console.log(response);
})
For the example you provided it would look like this (you did not include the Bearer
Prefix
axios.get('https://api.twitch.tv/helix/search/channels?query=loserfruit', {
headers: {
'Client-Id': 'mxciemz4ew',
'Authorization': 'Bearer vz9fcq1xv0qxxr7kcr2g9btubgdof'
}})
.then(function (response) {
console.log(response);
})