2017-01-23 164 views
0

如何将此代码导入到module.exports中?导入节点js错误

我很新的节点js和js。 我想,这个代码可以在其他航线

cache = (duration) => { 
    return (req, res, next) => { 
    let key = '__express__' + req.originalUrl || req.url 
    let cachedBody = mcache.get(key) 
    if (cachedBody) { 
     res.send(cachedBody) 
     return 
    } else { 
     res.sendResponse = res.send 
     res.send = (body) => { 
     mcache.put(key, body, duration * 1000); 
     res.sendResponse(body) 
     } 
     next() 
    } 
    } 
} 

我如何导出应用它呢?

我是这样的:

module.exports = cache = (duration) => { 
     return (req, res, next) => { 
     let key = '__express__' + req.originalUrl || req.url 
     let cachedBody = mcache.get(key) 
     if (cachedBody) { 
      res.send(cachedBody) 
      return 
     } else { 
      res.sendResponse = res.send 
      res.send = (body) => { 
      mcache.put(key, body, duration * 1000); 
      res.sendResponse(body) 
      } 
      next() 
     } 
     } 
    } 

我也尝试:

module.export = { 
    cache: function(duration) { 
    return (req, res, next) => { 
    let key = '__express__' + req.originalUrl || req.url 
    let cachedBody = mcache.get(key) 
    if (cachedBody) { 
     res.send(cachedBody) 
     return 
    } else { 
     res.sendResponse = res.send 
     res.send = (body) => { 
     mcache.put(key, body, duration * 1000); 
     res.sendResponse(body) 
     } 
     next() 
    } 
    } 
} 
} 

但是当我尝试在一个GET请求来使用它:

var expCache = require('../../middleware/cache'); 
    router.get('/:sid/fe',expCache.cache(3000),function(req,res) { 

它带来:

TypeError: expCache.cache is not a function 

问候

+2

* for循环与git *?对不起,这里的git在哪里? –

回答

1

您需要导出的对象,如果你期待能够调用expCache.cache

module.exports = { 
    cache: // your function 
} 

不过,如果你想保持你的输出模块,因为它是,刚刚通话像这样,而不是:

// inside middleware/cache: 
// module.exports = cache = (duration) => { 

var expCache = require('../../middleware/cache'); 

// you can call it as just a function 
router.get('/:sid/fe', expCache(3000), function(req,res) { 
+0

我明白这一点。但它标志着= =字符:SyntaxError:Unexpected token => – arnoldssss

+0

mah错误,谢谢 – arnoldssss

1

尝试

var expCache = require('../../middleware/cache'); 
router.get('/:sid/fe',expCache(3000),function(req,res) {.. 

您正在导出缓存功能,而不是包含它的对象(这是您尝试将它用于路由器的方式)。

+0

我试过了,但没有工作......它没有通过dthe文件 – arnoldssss