如何解决请求不通过 express 中间件
我正在为订阅者集成 Twitch API,并且在获取对中间件函数的 webhook 回调响应时遇到问题,它应该检查标头并验证签名。
我收到了正确的回复!然而,它就停在那里! 我检查了路线的顺序,但我不确定我错过了什么
我正在关注https://dev.twitch.tv/docs/eventsub
app.post('/createWebhook/:broadcasterId',(req,res) => {
const createWebHookParams = {
host: "api.twitch.tv",path: "helix/eventsub/subscriptions",method: 'POST',headers: {
"Content-Type": "application/json","Client-ID": clientId,"Authorization": "Bearer " + authToken
}
}
const createWebHookBody = {
"type": "channel.follow","version": "1","condition": {
"broadcaster_user_id": req.params.broadcasterId
},"transport": {
"method": "webhook","callback": "ngrokURL/notification","secret": webhookSecret //
}
}
let responseData = ""
const webhookReq = https.request(createWebHookParams,(result) => {
result.setEncoding('utf8')
result.on('data',(d) => {
responseData = responseData + d
})
.on('end',(result) => {
const responseBody = JSON.parse(responseData) // json
console.log(responseBody)
res.send(responseBody)
})
})
webhookReq.on('error',(e) => {
console.log("Error")
})
webhookReq.write(JSON.stringify(createWebHookBody))
webhookReq.end()
});
// middlewsre ---> // not triggered!!!
app.use(express.json({
verify: verifyTwitchSignature
}));
// making post to receeive the notification.
app.post('/notification',res) => {
console.log("incoming notificatin",req.body)
res.status(200).end();
})
// the middleware verifing the signature
const crypto = require("crypto");
const twitchSigningSecret = process.env.SECRET;
const verifyTwitchSignature = (req,res,buf,encoding)=>{
const messageId = req.header("Twitch-Eventsub-Message-Id");
const timeStamp = req.header("Twitch-Eventsub-Message-Timestamp")
const messageSignature = req.header("Twitch-Eventsub-Message-Signature")
console.log(`Message ${messageId} Signature: `,messageSignature)
if (!twitchSigningSecret){
console.log(`Twitch signing secret is empty`);
throw new Error ("Twitch signing secret is empty.");
}
const computedSignature = "sha256=" + crypto.createHmac("sha256",twitchSigningSecret).update(messageId + timeStamp + buf).digist("hex");
console.log(`Message ${messageId} Computed Signature: `,computedSignature)
if (messageSignature !== computedSignature) {
throw new Error("Invalid Signature.");
}else {
console.log("Verification Successful");
}
}
module.exports = verifyTwitchSignature
解决方法
我相信您的 verifyTwitchSignature
函数需要将 next
作为参数之一传递,并在传递调用 next();
时在 else 语句中传递。
这是我的观察。
如果您使用中间件,您总是必须将 next
与 req
和 res
一起传递。 next
调用队列中的下一个中间件或函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。