You need to enable JavaScript to run this app. TypeScript报错'string | string[]'不可赋值给string的firebase鉴权问题
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错'string | string[]'不可赋值给string的firebase鉴权问题

报错原因

Express 的 Request.headers 中所有字段的默认类型都是 string | string[] | undefined,你只做了非 undefined 判断,没有排除值为 string[] 类型的场景,所以赋值给显式声明为 string 类型的 token 变量时就会触发类型不匹配的报错。
另外你的代码还存在逻辑漏洞:当请求未携带 token 请求头时,不会进入if分支执行校验逻辑,会直接调用next()放行,等于身份校验中间件完全失效。

修正方案

先对请求头的取值做类型兼容处理,确保拿到的是字符串格式的token,同时补全无token的拦截逻辑,完整代码如下:

const isAuthenticated = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const tokenHeader = req.headers.token;
        // 兼容数组类型的请求头值,确保token为字符串类型
        const token = Array.isArray(tokenHeader) ? tokenHeader[0] : (tokenHeader ?? '');
        // 无token直接拦截返回401
        if (!token) {
            return res.status(401).json({ error: 'No token provided' });
        }
        // 校验token合法性
        await auth.verifyIdToken(token);
        // 校验通过放行
        return next();
    } catch (error) {
        res.status(401).json({
            error:'Invalid token'
        })
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 00:09:01