大家好!我需要发送http请求到twitch。它的工作原理:用户输入流线的名称,我的程序将http请求发送到twitch,输出需要是当前在twitch上的观看者的数量。我的尝试:
import fetch from 'node-fetch';
const response = await fetch('https://www.google.com/');
const data = await response.json();
console.log(data);
发布于 2022-08-31 08:04:52
我建议您使用像axios
这样的包来提出请求。这是因为要进行身份验证,您还需要发送一个POST requeust
,这使得axios变得非常容易。
首先,您需要对服务器进行身份验证,如下所示
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"
}
*/
})
您可以查询这样的频道。您可以找到您可以发出的所有请求以及它们的响应这里。同样,这里您需要提供上一步的身份验证。
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);
})
对于您提供的示例,它将如下所示(您没有包括Bearer
前缀)
axios.get('https://api.twitch.tv/helix/search/channels?query=loserfruit', {
headers: {
'Client-Id': 'mxciemz4ew',
'Authorization': 'Bearer vz9fcq1xv0qxxr7kcr2g9btubgdof'
}})
.then(function (response) {
console.log(response);
})
https://stackoverflow.com/questions/73547611
复制相似问题