Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/43.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我得到了一个错误;auth不是一个函数;在路由中调用my auth函数时_Javascript_Node.js_Reactjs_Express_Model View Controller - Fatal编程技术网

Javascript 我得到了一个错误;auth不是一个函数;在路由中调用my auth函数时

Javascript 我得到了一个错误;auth不是一个函数;在路由中调用my auth函数时,javascript,node.js,reactjs,express,model-view-controller,Javascript,Node.js,Reactjs,Express,Model View Controller,我有一个经过身份验证的函数,每当用户从后端请求敏感信息时,我都要调用该函数。我的问题是每次我调用这个函数它都不会运行。 这是我的auth函数 const auth = (req,res,next)=>{ try{ // First get the token. const token = req.header("token") const verified = jwt.verify(token,process.env.JWT_TOK

我有一个经过身份验证的函数,每当用户从后端请求敏感信息时,我都要调用该函数。我的问题是每次我调用这个函数它都不会运行。 这是我的auth函数

const auth = (req,res,next)=>{

    try{
        // First get the token.
        const token = req.header("token")
        const verified = jwt.verify(token,process.env.JWT_TOKEN);
        console.log(verified)
        if(!verified){
            return res.status(401).json({
                error : "Token verification failed, auth denied"
            })
        }
        // Add a user to the request, the token will have a id object.
        req.user = verified.id;
        next();
    } catch(err){
        return res.status(400).status({
            error : "something went wrong"
        })
    }
}
这就是我想叫它的地方

const getUserInfo = (req,res)=>{
    db.User.findById(req.user,(error,foundUser)=>{
        if(error) return console.log(error);
        res.json({
            status: 200,
            data: foundUser,
            requestedAt: new Date().toLocaleString()
        });
    });
}
我试着在getUserInfo函数中运行它,但它不起作用。我还尝试在getuserinfo函数中将其作为参数传递,但也没有成功。 我的路线是这样安排的
router.get(“/user”,ctrl.getUserInfo)

您需要在router.get(“/user”,ctrl.getUserInfo)中添加auth函数作为第二个参数,因为它是一个中间件。如果你想了解更多,你可以阅读


我的错误源于导出auth文件中的对象而不是函数
module.exports={auth}
告诉我auth不是函数错误。但当我将其更改为
module.exports=auth
时。它起作用了

你能详细说明一下当你试图在
getUserInfo
函数中调用它时的错误是什么吗?@restartman87嘿,所以我的问题是我在auth文件中导出了一个对象作为
module.exports={auth}
,它给了我
auth不是一个函数错误
。但当我将其更改为module.exports=auth时。它起作用了我没有尝试你的方式,但我的问题是,我在auth文件中导出了一个对象,作为
module.exports={auth}
,它给我的auth不是一个函数错误。但当我将其更改为module.exports=auth时。信息技术worked@Adil汗。。你的问题似乎已经解决了。。如果答案有效,请感谢:)
router.get("/user", auth ,ctrl.getUserInfo)