How do I access libraries I'm adding via requi

2019-08-22 15:37发布

问题:

I'm trying to require an external library in my Node app (Koa server). I'm adding njwt in my main server.js file var njwt = require('njwt');

But I can't access njwt, in my route handler function it gives an error saying njwt is undefined.

From this answer (https://stackoverflow.com/a/5809968), it seems that using strict mode in my main server.js file makes functions and variables defined in my imported file inaccessible.

But what's the workaround?

回答1:

If I am understanding correctly, all you need to do is change it to: var njwt = require('./njwt');

This is assuming you have already done an npm install in the njwt directory.



回答2:

I think the issue is how to send njwt instance to your router, You can pass njwt instance like this,

require('./routes')(njwt);



回答3:

I'm not sure if this is the best approach. I just ended up requiring the library in the route handler

const router = require('koa-router')();
router.post('/register', async function(ctx, next) {
    var jwt = require('jsonwebtoken');
    debugger;

And I'm able to access the library this way (the other two methods didn't work for me).