获取错误CreateListFromArrayLike在尝试使用.apply()时调用非对象

Dat*_*sik 31 javascript

我已经创建了一个简单的小路径解析函数,这样我就可以保持我的代码干净并且易于维护,这是在应用程序启动并运行并解析config.json相应方法和请求路径时运行的小函数:

const fs = require('fs');
const path = require('path');
module.exports = function(app, root) {
  fs.readdirSync(root).forEach((file) => {
    let dir = path.resolve(root, file);
    let stats = fs.lstatSync(dir);
    if (stats.isDirectory()) {
      let conf = require(dir + '/config.json');
      conf.name = file;
      conf.directory = dir;
      if (conf.routes) route(app, conf);
    }
  })
}

function route(app, conf) {
  let mod = require(conf.directory);

  for (let key in conf.routes) {
    let prop = conf.routes[key];
    let method = key.split(' ')[0];
    let path = key.split(' ')[1];

    let fn = mod[prop];
    if (!fn) throw new Error(conf.name + ': exports.' + prop + ' is not defined');
    if (Array.isArray(fn)) {
      app[method.toLowerCase()].apply(this, path, fn);
    } else {
      app[method.toLowerCase()](path, fn);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是有时我需要将多个参数传递给快速路由器,例如在使用这样的护照的情况下:

exports.authSteam = [
  passport.authenticate('facebook', { failureRedirect: '/' }),
  function(req, res) {
    res.redirect("/");
  }
];
Run Code Online (Sandbox Code Playgroud)

所以我想我可以将它们作为数组传递,然后适当地将它们解析到路由器中,我的配置例如如下所示:

{
  "name": "Routes for the authentication",
  "description": "Handles the authentication",
  "routes": {
    "GET /auth/facebook": "authFacebook",
    "GET /auth/facebook/return": "authFacebookReturn"
  }
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是我收到此错误:

     app[method.toLowerCase()].apply(this, path, fn);
                                ^

TypeError: CreateListFromArrayLike called on non-object
Run Code Online (Sandbox Code Playgroud)

如果我,console.log(fn)我明白了[ [Function: authenticate], [Function] ]

我不确定我做错了什么,任何信息都会非常感谢.

小智 60

您需要将params作为数组发送,如下所示:

app[method.toLowerCase()].apply(this, [path, fn]);

如果要发送参数列表,则需要使用call:

app[method.toLowerCase()].call(this, path, fn);

来源:致电,申请

  • **a**pply **a**数组和 **c**all **c**逗号分隔的列表 (5认同)