从标头获取令牌时,req.headers.split不是函数

时间:2018-02-15 18:06:47

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

我正在尝试使用此处的代码示例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可以是string以及string[]。我该如何让这个工作?感谢。

1 个答案:

答案 0 :(得分:2)

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

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

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