我为网络框架选择ExpressJs
这是我的app.js文件(入口点)
const express = require('express')
const axios = require('axios')
const app = express()
const twitchClientSecret = process.env.twitchAppToken || require('./creditentials.json').twitchAppToken
const twitchClientID = process.env.twitchClientId || require('./creditentials.json').twitchClientId
app.use(express.static(__dirname + '/public'));
app.get('/twitch-oauth', (req, res) => {
console.log("hey")
const requestToken = req.query.code
console.log("requesttoken:" + requestToken)
// if (req.query.code) {
axios({
method: 'post',
url: `https://id.twitch.tv/oauth2/token?client_id=${twitchClientID}&client_secret=${twitchClientSecret}&code=${requestToken}&grant_type=authorization_code&redirect_uri=localhost:8080/twitch-oauth`,
headers: {
accept: 'application/json'
}
}).then((response) => {
console.log(response)
console.log("response" + response)
const accessToken = response.data.access_token
res.cookie('twitch_id_token', accessToken)
res.redirect('/')
}).catch((error) => {
// Error 😨
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
// }
})
// Start the server on port 8080
app.listen(8080)
这是我的index.html(带有HTTP
__dirname + '/public'
的文件)<a id="twitch-auth" href="https://id.twitch.tv/oauth2/authorize?client_id=6mrxy6lqs4m9svcim8ssr44ypzvk1c&redirect_uri=http://localhost:8080/twitch-oauth&response_type=code&scope=user:read:email&state=">
Login with Twitch
</a>
<script>
document.querySelector("#twitch-auth").href = document.querySelector("#twitch-auth").href + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
</script>
<script src="logic.js"></script>
最后是我的logic.js文件
const token = Cookies.get('twitch_id_token')
var cookie = document.cookie;
console.log(token);
if (token) {
fetch('https://api.twitch.tv/helix/users?id=44322889', {
method: 'GET',
headers: {
Accept: '*/*',
Authorization: 'Bearer ' + token,
}
})
// Parse the response as JSON
.then(res => res.json())
.then(res => {
console.log(res)
});
}
问题
当我单击“使用Twitch登录”按钮时,axios发出此请求时出现http错误:
https://id.twitch.tv/oauth2/token?client_id=${twitchClientID}&client_secret=${twitchClientSecret}&code=${requestToken}&grant_type=authorization_code&redirect_uri=localhost:8080/twitch-oauth
我返回
{status: 400, message: "Parameter redirect_uri does not match registered URI"}
有人能帮我吗 ?感谢您的回复
最佳答案
{status: 400, message: "Parameter redirect_uri does not match registered URI"}
响应基本上告诉您:'错误的请求',因为您的请求中包含
redirect_uri
参数。localhost:8080/twitch-oauth
尚未注册为有效的重定向URI 。您可能必须转到OAuth部分,并将
localhost:8080/twitch-oauth
设置为有效的redirect_uri
,因此Twitch平台将允许重定向并正确处理请求。从Twitch开发文档:
希望这可以解决您的问题。
祝好运!
关于javascript - NodeJS-如何将twitch API与OAuth和代码 token 一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56673080/