i am trying to set up an user level authentication using node.js, so i go and do npm install -g jsonwebtoken —save. However, i run into problems when i use require(‘jsonwebtoken’); and try to compile my code, it gives me the error described above in the title. Now, for some reason, when i uninstall the JWT and try to run my code without it, it compiles, but obviously it doesn’t work. I tried re-installing it, still no success.
My npm —version
6.3.0
node —version
v11.1.0
npm install -g jsonwebtoken —save
+ jsonwebtoken@8.4.0
code:
'use strict';
require('jsonwebtoken');
exports.generateToken = async (data) => {
return jwt.sign(data, global.SALT_KEY, { expiresIn: '1d' });
}
exports.decodeToken = async (token) => {
var data = await jwt.verify(token, global.SALT_KEY);
return data;
}
exports.authorize = function (req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (!token) {
res.status(401).json({
message: 'Acesso Restrito'
});
} else {
jwt.verify(token, global.SALT_KEY, function (error, decoded) {
if (error) {
res.status(401).json({
message: 'Token Inválido'
});
} else {
next();
}
});
}
};
exports.isAdmin = function (req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (!token) {
res.status(401).json({
message: 'Token Inválido'
});
} else {
jwt.verify(token, global.SALT_KEY, function (error, decoded) {
if (error) {
res.status(401).json({
message: 'Token Inválido'
});
} else {
if (decoded.roles.includes('admin')) {
next();
} else {
res.status(403).json({
message: 'Esta funcionalidade é restrita para administradores'
});
}
}
});
}
};
Hello!
I’ve been working on a personal project, and I’m currently trying to implement JWT authentication (following this tutorial: https://www.youtube.com/watch?v=LKlO8vLvUao&t=5544s) but unfortunately I keep running into the following error:
internal/modules/cjs/loader.js:895throw err;Error: Cannot find module 'jsonwebtoken'
Require stack:- /app/controllers/users.js- /app/routes/users.js- /app/index.js
The imports in my /app/controllers/users.js file are as follows:
const jwt = require('jsonwebtoken');const bcrypt = require('bcryptjs');const User = require('../models/user.js');
When I swap the order of the jwt and bcrypt import, then the error message changes to reflect that (i.e., it cannot find module ‘bcryptjs’ if that is first). However, there are no issues when importing my own models/user.js file.
I have uninstalled and re-installed the node_modules folder several times, and my package.json file seems to be totally fine (I think):{"name": "server","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "nodemon index.js","test": "echo "Error: no test specified" && exit 1"},"keywords": [],"author": "","license": "ISC","dependencies": {"bcryptjs": "^2.4.3","body-parser": "^1.19.0","cors": "^2.8.5","express": "^4.17.1","jsonwebtoken": "^8.5.1","mongoose": "^5.12.3","nodemon": "^2.0.7"}}
Apologies for the wall of text — any ideas? I’ve scoured dozens of SO posts, but unfortunately to no avail.
Thank you!
UPDATE: I think it may be something to do with docker/docker-compose. When I run npm start
in my server directory, I no longer get a ‘Cannot find module’ error. I only get it after running docker-compose up
. I still haven’t figured out a fix yet though.
UPDATE #2 (for anyone from the future with this issue): I finally fixed it. Instead of just doing docker-compose build
followed by docker-compose up
, do the following sequence:docker-compose build
docker-compose down -v
<— This removes all volumesdocker-compose up
Thanks to M3RS from https://stackoverflow.com/questions/42040317/cannot-find-module-for-a-node-js-app-running-in-a-docker-compose-environment for the solution.
#node.js #git #amazon-web-services #debugging #jwt
#node.js #git #amazon-веб-сервисы #отладка #jwt
Вопрос:
Итак, у меня проблема, вот она :
- У меня есть серверное приложение (скажем, /), которое бесперебойно работает на локальном
- Когда я подключаюсь к AWS, приложение выдает :
Error: Cannot find module 'jsonwebToken'
Вот предыстория :
Перед тем, как перенести приложение в AWS, у меня уже есть другое приложение (скажем, B /), которое также необходимо jsonwebtoken
, и оно работает без сбоев.
Вот что я пробовал :
- После извлечения я удаляю
package-lock.json
иnpm i
повторяю ту же ошибку - Я удалил
jsonwebtoken
папку внутриnode_modules
, все та же ошибка - Я создаю новый экземпляр в AWS, заново устанавливаю узел, npm, mongo, все та же ошибка
- Я удаляю
jsonwebtoken
папку в /node_modules
и делаюcp -r ~/from/node_modules/jsonwebtoken ~/to/node_modules/jsonwebtoken
, все та же ошибка - Я не использовал
jsonwebtoken
модуль, приложение работает без сбоев
Вот где мне нужна помощь:
- Есть ли какие-либо известные ошибки в отношении
jsonwebtoken
? - Проблема не в этом
jsonwebtoken
?
Osman Forhad
Posted on Mar 3, 2022
• Updated on Mar 26, 2022
trying to run node js project which is develop in express js and other necessary library. after writing code when i decide to run the project then i wrote the command npm start and alternatively nodemon command. its show me an error which is below screenshot:
after this happening i was thinking and search why this is happen and why terminal show me node:internal/modules/cjs/loader:936
throw err;
^
after wasting few times i find out and figured the mistake which is done by me. so i decide to share this with all of you guys (the internet people)
.
so what was the mistake did by me: it was a case of trying to run the file in node from the wrong location.
do you understand.? if answer is no. well i explain here don’t worry: here rbac is my project directory and there i have another directory which name was server and inside the server directory i have a file which name also server.js, please keep in mind this is the main point of my mistake.
.
to run this project i need to hit** server.js file by using npm start or nodemon*. in this case i was open my termial inside my main directory which name rbc as i mentioned in previous line and from here i tried to hit server.js file but this file is not in this location. the actual location of server.js file is inside **rbac/server/server.js *
so the terminal show me node:internal/modules/cjs/loader:936
throw err;
^
and when i realize my mistake then i just move server.js file from rbac/server/server.js to rbac/server.js
and then open terminal inside the project root and then run nodemon or npm star and now it’s working fine. finally my terminal look like below screenshot and this is the actual view which i want to see.
.
Happy Coding.
osman forhad
Full-Stack Developer💻 (Mobile App & Web App)
developer.osmanforhad@gmail.com
Good day! I am testing an AWS Lambda Function that uses an AWS Lambda Layer with the following directory:
LambdaLayer.zip
nodejs/
package.json
package-lock.json
node_modules/
jsonwebtoken/
In my Lambda Function (running on node 14.x runtime), I am importing the module from the layer like this:
const jwt = require('jsonwebtoken');
However, I am getting the following error:
ERROR Uncaught Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'jsonwebtoken'nRequire stack:n- /var/task/index.jsn- /var/runtime/UserFunction.jsn- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module 'jsonwebtoken'","Require stack:","- /var/task/index.js","- /var/runtime/UserFunction.js","- /var/runtime/index.js","
I already followed the directory structure as per AWS documentation and as also stated here: AWS lambda layers error when call API «cannot find module». Still, I’m getting this error.
I also tried the below directory structure but still did not work:
LambdaLayer.zip
nodejs/
node14/
node_modules/
jsonwebtoken/
Am I missing something?
P.S. I have compressed the directory using zip -r LambdaLayer.zip LambdaLayer/ and also uploaded it to Lambda layer manually via the AWS Console.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.