2016-12-28 22 views
10

Kodumu temiz ve kolay bir şekilde saklayabilmem için basit bir küçük yol ayrıştırma işlevi oluşturdum. Uygulamanın başlatılması ve config.json dosyayı ayrıştırır ve uygun yöntemler ve istek yolları bağlar:Başlarken GetListFromArrayLike kullanılmaya çalışırken nesneye çağrılmadı .apply()

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

Ben sorun ben bir ekspres yönlendirici, örneğin birden fazla argüman olarak geçmesi gereken bazı katıdır Böyle pasaport şey kullanılması durumunda:

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

Yani ben sadece bir dizi olarak onları geçebilir anlamaya ve sonra yönlendirici içine ayrıştırmak uygun, örneğin benim yapılandırma şöyle görünür:

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

bkz console.log(fn) eğer

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

TypeError: CreateListFromArrayLike called on non-object 

:

tek sorun bu hatayı alıyorum edilir

Neyi yanlış yaptığımı tam olarak bilmiyorum, herhangi bir bilgi çok teşekkür ederim.

cevap

21

Bunu, bir dizi olarak params'ı göndermek gerekir:

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

Kaynak:

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

bir argümanlar aramayı kullanmak gerekir listelemek göndermek istiyorsanız : call, apply