本文介绍了如何使模块(例如bcrypt)在Express中全局可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个路由"文件,我在其中导入如下模块:

I have several "routes" files where I import modules like this:

var bcrypt = require('bcryptjs');

我试图通过将bcrypt导入到我的主应用js中,然后使用app.use()来使bcrypt在全球范围内可用:

I have attempted to make bcrypt available globally by importing it into my main app js and then using an app.use() something like this:

var bcrypt = require('bcryptjs');
app.use(bcrypt); // clearly not right, app crashes

我在这里尝试了多种方法.我应该坚持将其分别导入到每个文件中吗,还是有一种很好的方法使该模块在全球范围内可用?

I've tried a variety of things here. Should I just stick with importing this into every file separately or is there a good way to make this module available globally?

推荐答案

app.use 仅适用于Express中间件,而 bcrypt 则不能,它只是一个常规的Node.js模块.

app.use will only work with an Express middleware, which bcrypt is not, it's just a regular Node.js module.

正如评论中所指出的那样,您没有任何理由不应该仅使用 require 使 bcrypt 在需要它的任何模块中可用.

As was pointed out in the comments, there is not really any reason why you shouldn't just use require to make bcrypt available in any module that needs it.

对于它的价值,您可以使用全局可用变量全局创建Node.js中的全局变量.

For what it's worth, you can use the globally available variable global to create a global variable in Node.js.

在您的示例中,将按以下方式使用它(但再次,这是不推荐):

In your example, it would be used like this (but again, this is NOT RECOMMENDED):

var bcrypt = require('bcryptjs');
global.bcrypt = bcrypt;

这篇关于如何使模块(例如bcrypt)在Express中全局可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 06:42