【问题标题】:UnhandledPromiseRejectionWarning: TypeError: UserService.authenticate is not a functionUnhandledPromiseRejectionWarning: TypeError: UserService.authenticate is not a function
【发布时间】:2021-10-01 11:01:08
【问题描述】:

我正在尝试使用 knex express 和 mysql 对我的 api 项目实施基本身份验证。

我有以下功能


const users = [{ id:1, username:'selia', password:'fullservice'}]



function authenticate({ username, password}) {
    const user = users.find(u => u.username === username && u.password === password)
    if(user) {
        const {password, ...userWithoutPassword} = user
        return userWithoutPassword
    }
}

module.exports  = authenticate

const userService = require('../users/user.service.js')





async function basicAuth(req,res,next){
    // checando basic auth
    if(!req.headers.authorization || req.headers.authorization.indexOf('Basic') === -1) {
        return res.status(403).json({ message: 'Header de Autorizacao nao encontrado'})
    }

    //verificando basuc auth

    const base64Credentials = req.headers.authorization.split('')[1]
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii')
    const [username, password] = credentials.split(':')
    const user = await userService.authenticate({ username, password})
    if (!user){
        return res.status(403).json({ message: 'Usuario e/ou senha invalidos'})
    }

    //atribuindo usuario no objeto da requisicao
    req.user = user

    next();
}

module.exports = basicAuth

这是我的索引

const express = require('express')
const routes = require('./routes')
const basicAuth = require('./helpers/basic-auth')

const app = express()
app.use(basicAuth)
app.use(routes)






app.listen(3333, ()=> console.log('Server is running'))

当我运行它时,我得到了这个错误

(node:7488) UnhandledPromiseRejectionWarning: TypeError: userService.authenticate is not a function
    at basicAuth (/home/matheus/projeto/src/helpers/basic-auth.js:18:30)
    at Layer.handle [as handle_request] (/home/matheus/projeto/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/matheus/projeto/node_modules/express/lib/router/index.js:317:13)
    at /home/matheus/projeto/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/matheus/projeto/node_modules/express/lib/router/index.js:335:12)
    at next (/home/matheus/projeto/node_modules/express/lib/router/index.js:275:10)
    at expressInit (/home/matheus/projeto/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/home/matheus/projeto/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/matheus/projeto/node_modules/express/lib/router/index.js:317:13)
    at /home/matheus/projeto/node_modules/express/lib/router/index.js:284:7
(node:7488) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7488) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

当我对失眠进行获取请求时收到此错误

我相信这与我的异步功能有关,但我不知道如何解决这个问题

对不起我的英语不好

【问题讨论】:

    标签: javascript node.js async-await authorization knex.js


    【解决方案1】:

    考虑到你是如何导出和导入函数的,这行是不正确的:

    const user = await userService.authenticate({ username, password})
    

    应该是:

    const user = await userService({ username, password})
    

    因为您的 user.service.js 模块导出的是函数,而不是具有 authenticate 属性的对象。

    【讨论】:

    • 你的逻辑是正确的谢谢,我做了不同的但它也可以工作我把这个''' module.exports = authenticate '''改为这个module.exports = {authenticate}