You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用coro-http的Lua Twitch OAuth2请求仍未授权,如何解决?

问题分析与解决方案

你的Lua代码出现未授权问题,核心原因是coro-http库对请求头的格式要求和你当前的写法不匹配。coro-http要求headers参数是一个数组,每个元素是包含头字段名和值的子数组,而不是普通的键值对table。

修正后的代码

local http = require("coro-http")
local json = require("json")

local url = "https://id.twitch.tv/oauth2/token"
local client_id = "<>"
local client_secret = "<>"

-- 修正POST请求的headers格式:数组形式的键值对
local post_headers = {
    {"Content-Type", "application/x-www-form-urlencoded"}
}

local body = "client_id=" .. client_id .. "&client_secret=" .. client_secret .. "&grant_type=client_credentials"

local response, w = http.request("POST", url, post_headers, body)
-- 检查token请求是否成功
if response.code ~= 200 then
    print("获取token失败,响应码:", response.code)
    print("响应内容:", w)
    return
end

local data = json.decode(w)
local access_token = data.access_token

-- 修正GET请求的headers格式
local get_headers = {
    {"Client-ID", client_id},
    {"Authorization", "Bearer " .. access_token}
}

local response, b = http.request("GET", "https://api.twitch.tv/helix/channels?broadcaster_id=141981764", get_headers)
print("GET请求响应码:", response.code)
print(b)

关键修改点说明

  • 将headers从键值对table改为数组格式,每个头字段用{"字段名", "字段值"}的形式定义,这是coro-http库的强制要求。
  • 添加了token请求的响应状态码检查,方便快速排查token获取失败的情况。

内容的提问来源于stack exchange,提问作者kydie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 00:45:49