How do I access libraries I'm adding via require, in my Node/Koa server

人走茶凉 提交于 2019-12-11 14: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).



来源:https://stackoverflow.com/questions/47406325/how-do-i-access-libraries-im-adding-via-require-in-my-node-koa-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!