await 仅在异步函数和模块的顶层主体中有效 javascript express error

RIFKY MANUEL SATYANA SATYANA

此代码用于验证 Firebase 身份验证。首先,它检查 req.headers。然后从令牌中检索 uid。收到decodedToken.uid后,代码会与自己的MySQL数据库核对,获取用户使用getID(uid)函数的id。如果 uid 不在数据库中,它将使用函数创建一个新用户makeNewUser()执行时,代码返回“等待仅在异步函数和模块的顶层主体中有效”的错误。我怎样才能解决这个问题?我应该创建一个新文件来处理这些东西,并且该代码的返回应该存储在 res.locals 中吗?这是代码。


const admin = require('./config/firebaseAuth'); // import admin from firebase initializeApp
const getId = require('../utils/getUserID'); // module to get userId form MySQL database
const makeNewUser = require('../utils/makeNewUser'); // module to make a new user into MySQL database


class Middleware {
    async decodeToken(req,res,next) {
        // get authorization from the headers
        const { authorization } = req.headers; 

        // check if the authorization headers are well configured
        // this includes checking if headers.authorization exist
        // then if the format in headers.authorization matches with the configured
        if (!authorization) return res.status(403).json({
            status: 'fail', 
            type: 'server/missing-authorization',
            message: 'Missing req.headers.authorization on request to the server. This is need for authorization!'
        })

        else if (!authorization.startWith('Bearer')) return res.status(400).json({
            status: 'fail', 
            type: 'server/missing-bearer',
            message: 'Missing Bearer in req.headers.authorization on request to the server. This is needed to extract the token!'
        })

        else if (authorization.split(' ').length !== 2) return res.status(400).json({
            status: 'fail',
            type: 'server/bearer-unrecognized',
            message: 'Bearer in req.headers.authorization is not well configured. This is need to extract the token!'
        })
        // after passing the authorization header checks, now checks the token
        const token = authorization.split(' ')[1]; // req.headers = {"Bearer $.token"} 
        admin.auth().verifyIdToken(token)
            .then((decodedToken) => {
                const {uid, name} = decodedToken; // get uid and name from the token
                try {
                    // !this produces an error: await is only valid in async functions and the top level bodies of modules
                    const result = await getId(uid); // getId to get the id of the user regarding the uid
                    // check if exist uid in the database
                    if (result.length < 1) {
                        // if not make a new user
                        const result = await makeNewUser(uid, name); // make new user from the given uid and name
                        const id = result.insertId; // get the id of the new user
                        req.user = {id: id, name: name}; // set id and name to req.user
                        return next();
                    }
                    const id = result[0].id; // getId to get the id of the user from the result query since uid exist
                    req.user = {id: id, name: name}; // set id and name to req.user 
                    return next();
                } catch (err) {
                    return res.status(500).json({
                        status: 'fail',
                        type: 'database/fail-to-query',
                        message: err.message
                    })
                }
            })
            .catch((err) => {
                /*
                on err for firebase tokens, such as sent was FMC token instead of id token or token has expired and many others!
                err response: after executing console.log(err)
                {
                    errorInfo: {
                    code: 'auth/argument-error',
                    message: 'Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
                    },
                    codePrefix: 'auth'
                }
                or
                {
                    errorInfo: {
                        code: 'auth/id-token-expired',
                        message: 'Firebase ID token has expired. Get a fresh ID token from your client app and try again (auth/id-token-expired). See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
                    },
                    codePrefix: 'auth'
                }
                */
                if (err.errorInfo.code === 'auth/internal-error') var statusCode = 500;
                else var statusCode = 400; 
                return res.status(statusCode).json({status: "fail", type: err.errorInfo.code, message: err.errorInfo.message}); // return with status codes
            })
    }
}

module.exports = new Middleware();

注意:getId 和 makeNewUser 返回一个承诺!

吉滕德拉·乔汉

用这个

const admin = require('./config/firebaseAuth'); // import admin from firebase initializeApp
    const getId = require('../utils/getUserID'); // module to get userId form MySQL database
    const makeNewUser = require('../utils/makeNewUser'); // module to make a new user into MySQL database
    
    
    class Middleware {
        async decodeToken(req,res,next) {
            // get authorization from the headers
            const { authorization } = req.headers; 
    
            // check if the authorization headers are well configured
            // this includes checking if headers.authorization exist
            // then if the format in headers.authorization matches with the configured
            if (!authorization) return res.status(403).json({
                status: 'fail', 
                type: 'server/missing-authorization',
                message: 'Missing req.headers.authorization on request to the server. This is need for authorization!'
            })
    
            else if (!authorization.startWith('Bearer')) return res.status(400).json({
                status: 'fail', 
                type: 'server/missing-bearer',
                message: 'Missing Bearer in req.headers.authorization on request to the server. This is needed to extract the token!'
            })
    
            else if (authorization.split(' ').length !== 2) return res.status(400).json({
                status: 'fail',
                type: 'server/bearer-unrecognized',
                message: 'Bearer in req.headers.authorization is not well configured. This is need to extract the token!'
            })
            // after passing the authorization header checks, now checks the token
            const token = authorization.split(' ')[1]; // req.headers = {"Bearer $.token"} 
            admin.auth().verifyIdToken(token)
                .then( async (decodedToken) => {
                    const {uid, name} = decodedToken; // get uid and name from the token
                    try {
                        // !this produces an error: await is only valid in async functions and the top level bodies of modules
                        const result = await getId(uid); // getId to get the id of the user regarding the uid
                        // check if exist uid in the database
                        if (result.length < 1) {
                            // if not make a new user
                            const result = await makeNewUser(uid, name); // make new user from the given uid and name
                            const id = result.insertId; // get the id of the new user
                            req.user = {id: id, name: name}; // set id and name to req.user
                            return next();
                        }
                        const id = result[0].id; // getId to get the id of the user from the result query since uid exist
                        req.user = {id: id, name: name}; // set id and name to req.user 
                        return next();
                    } catch (err) {
                        return res.status(500).json({
                            status: 'fail',
                            type: 'database/fail-to-query',
                            message: err.message
                        })
                    }
                })
                .catch((err) => {
                    /*
                    on err for firebase tokens, such as sent was FMC token instead of id token or token has expired and many others!
                    err response: after executing console.log(err)
                    {
                        errorInfo: {
                        code: 'auth/argument-error',
                        message: 'Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
                        },
                        codePrefix: 'auth'
                    }
                    or
                    {
                        errorInfo: {
                            code: 'auth/id-token-expired',
                            message: 'Firebase ID token has expired. Get a fresh ID token from your client app and try again (auth/id-token-expired). See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
                        },
                        codePrefix: 'auth'
                    }
                    */
                    if (err.errorInfo.code === 'auth/internal-error') var statusCode = 500;
                    else var statusCode = 400; 
                    return res.status(statusCode).json({status: "fail", type: err.errorInfo.code, message: err.errorInfo.message}); // return with status codes
                })
        }
    }
    
    module.exports = new Middleware();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

控制台错误:await 仅在异步函数和模块的顶层主体中有效

SyntaxError: await 仅在异步函数和模块的顶层主体中有效。不和谐,js

Javascript 函数 await 仅在异步函数中有效

ASYNC / AWAIT SyntaxError:await 仅在异步函数和模块的顶级主体中有效

获取 SyntaxError: await 仅在异步函数和模块的顶层主体中有效,同时通过 discord.js 指南工作

for循环中的“ await仅在异步函数中有效”

For 循环 - SyntaxError: await 仅在异步函数中有效

给出 await 的异步函数仅在异步函数中有效

“await 仅在异步函数中有效”,而它是一个异步函数

await 总是抛出 SyntaxError: await 仅在 sequelize 的异步函数中有效

Javascript:SyntaxError:等待仅在异步函数中有效

Google Cloud / Firebase 函数:await 仅在异步函数中有效

SyntaxError:await 仅在带有 Apify Metamorph 的异步函数中有效

await 仅在异步函数 discord.js 中有效

Await仅在使用Node.js的异步函数中有效

“await 仅在异步函数中有效” discord.js

Sails.js SyntaxError:await 仅在异步函数中有效

await 仅在异步函数 Discord bot 反应角色中有效

即使等待位于 Node.js 中的异步函数中,如何修复“await 仅在异步函数中有效”?

`SyntaxError:await 仅在异步函数中有效`,同时尝试在 node rest api 中注册用户

await仅在异步功能中有效-异步中的eval

未捕获的 SyntaxError:await 仅在 async 函数中的 async 函数中有效

SyntaxError:“await”仅在“async”函数中有效 - 需要帮助

SyntaxError:await 仅在 async 函数中有效,但 async 已包含在内

为什么我的 await 在我的功能中不起作用?“语法错误:等待仅在异步函数中有效”

Javascript / Nodejs在Node.js模块的顶层使用await

SyntaxError:当使用Node JS连接到Mongo DB时,await仅在异步功能中有效

Mongodb async await with express

NodeJS Express应用程序等待仅在异步功能中有效,但这显然是异步功能吗?