【问题标题】:req.headers.split is not a function when getting token from header从标头获取令牌时,req.headers.split 不是函数
【发布时间】:2018-07-26 14:09:51
【问题描述】:

我正在尝试使用此处 https://github.com/firebase/functions-samples/blob/master/authorized-https-endpoint/functions/index.js 的代码示例,但我的云功能不断崩溃说

req.headers.split is not a function
    at cors (/user_code/index.js:25:37)
    at cors (/user_code/node_modules/cors/lib/index.js:188:7)
    at /user_code/node_modules/cors/lib/index.js:224:17
    at originCallback (/user_code/node_modules/cors/lib/index.js:214:15)
    at /user_code/node_modules/cors/lib/index.js:219:13
    at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
    at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
    at exports.savedProfiles.functions.https.onRequest (/user_code/index.js:14:5)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:41)
    at /var/tmp/worker/worker.js:671:7

我不确定如何让它工作。这是我目前使用的代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});

exports.savedProfiles = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        if ((!req.headers.authorization || !req.headers.authorization.includes('Bearer '))) {
            console.log(req.headers);
            console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.');

            res.status(403).send('Unauthorized');
            return;
        }

        const tokenId = req.headers.split('Bearer ')[2];
        res.status(200).send('Testing');
        return;
    });
});

我知道错误是由于req.headers.split('Bearer ')[2]; 导致的,它只是从标头中获取令牌。但我认为问题在于 req.headers 可以是stringstring[]。我将如何让这个工作?谢谢。

【问题讨论】:

    标签: javascript firebase firebase-authentication google-cloud-functions


    【解决方案1】:

    req.headers 始终是由标头名称索引的对象,而不是字符串。您提到的代码是这样做的:

    req.headers.authorization.split('Bearer ')[1]
    

    它正在访问“Authorization”标头,这是一个字符串,然后将其拆分。

    【讨论】:

    • 那么正确的做法是什么?由于这是示例代码中写的内容
    • 您的代码使用的是req.headers.split,而不是req.headers.authorization.split
    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 2019-07-22
    • 2021-07-27
    • 1970-01-01
    • 2020-11-16
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多