获取错误CreateListFromArrayLike在尝试使用.apply()时调用非对象 [英] Getting error CreateListFromArrayLike called on non-object when trying to use .apply()

查看:83
本文介绍了获取错误CreateListFromArrayLike在尝试使用.apply()时调用非对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created a simple little route parsing function so that I can keep my code clean and easily maintainable, this is the little function that gets ran when the app starts up and parses the config.json file and binds the appropriate methods and request paths:

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);
    }
  }
}

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

The problem I have is some times I need to pass in multiple arguments to an express router, e.g. in the case of using passport something like this:

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

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

So I figure I can just pass them as an array, and then parse them into the router appropriately, my config for example looks like this:

{
  "name": "Routes for the authentication",
  "description": "Handles the authentication",
  "routes": {
    "GET /auth/facebook": "authFacebook",
    "GET /auth/facebook/return": "authFacebookReturn"
  }
}

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

The only problem is I'm getting this error:

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

TypeError: CreateListFromArrayLike called on non-object

如果我 console.log(fn)我看到 [[功能:验证],[功能]]

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

I'm not exactly sure what I am doing wrong, any information would be great thanks.

推荐答案

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

You need to send the params as an array, like this:

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

如果你想发送一个参数列表,你需要使用call:

If you want to send an arguments list you need to use call:

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

来源:致电申请

这篇关于获取错误CreateListFromArrayLike在尝试使用.apply()时调用非对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆