【问题标题】:Getting TypeError: validatetoken is not a function获取 TypeError:validatetoken 不是函数
【发布时间】:2026-01-08 23:30:01
【问题描述】:

我使用以下方法在将某些数据发送到其他地方之前对其进行验证,我有一个函数 validate 用于检查其他两个函数(validatetoken 和 validate_added_mods)是否在 validate 返回 true 之前返回 true。

我的问题是,当验证函数尝试调用其他函数说它们实际上不是函数时,我得到一个类型错误,我对 JS 很陌生,所以我可能有一些明显的盲点!提前致谢

'use strict';
const config = require('./config');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const fs = require('fs');
const {body, validationResult} = require('express-validator');
const jwt_decode = require('jwt-decode');
const e = require('express');

class validator{
    constructor(
    token,
    email,
    addedmodtoken,
    current_modules,
    removed_mod_codes
    ){
        this.token = token;
        this.email = email;
        this.addedmodtoken = addedmodtoken;
        this.current_modules = current_modules;  
        this.removed_mod_codes = removed_mod_codes;
    }

    validate(validatetoken, validate_added_mods,token,email) {
        return new Promise((resolve, reject)=>{
            try {
                if(validatetoken(token, email) && validate_added_mods(addedmodtoken, email)){
                    resolve(true)

              } else {
                reject;
              };
          } catch(e) {
            reject(e);
          }
        });
    }

    validatetoken(token, email) {
        var decoded = jwt_decode(token);
        var jwtemail = decoded.id;
        return new Promise((resolve, reject)=>{
            try {
                if (email === jwtemail){
                    console.log("Validated token! ");
                    resolve(true);
                } else {
                reject;
              };
          } catch(e) {
            reject(e);
          }
        });
    }
 
    validate_added_mods(addedmodtoken, email) {
        var decoded = jwt_decode(addedmodtoken);
        var jwtemail = decoded.id;
        return new Promise((resolve, reject)=>{
            try {
                if(jwtemail === email){
                    console.log("Validated added modules! ");
                    resolve(true);
                        
                } else {
                reject;
              };
          } catch(e) {
            reject(e);
          }
        });
    }
}

module.exports = validator; 

【问题讨论】:

  • 您不一定要调用您的validatetoken 函数,因为它实际上是传递给validatetoken 函数的validatetoken 参数的值。与validate_added_mods 相同

标签: javascript node.js json jwt


【解决方案1】:

你是怎么调用 validate() 的?

您的 validate() 函数接受四个参数:validatetoken、validate_added_mods、token 和 email。

当您调用 validate 时,您必须传递一个函数作为第一个参数,因为您在几行之后将此参数用作函数。

如果您打算使用稍后定义的名为 validatetoken 的函数,那么您可能希望从 validate() 接受的参数列表中删除 validatetoken。

请记住,具有相同名称的符号不一定是相同的符号。范围也必须相同。

(变量和函数名都是符号)

【讨论】: