ES6 imports for JWT

こ雲淡風輕ζ 提交于 2021-01-29 07:17:59

问题


I'm making a nodeJS web app and I'm using JWT for authentication. All my work is in ES6 modules and I wanted to import JWT in the same way, but apparently it isn't yet supported by the package. I can't use the older require() format as it throws an error since I've set it to modules in my package.json. Is there a way around this or do I have to find another library altogether?

Edit: I have fixed the issue with destructuring but it's still not working. Apparently it can't find the module at all. I made sure the package is in fact installed and updated, still not working

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonwebtoken' imported from /path/to/file.js

import jwt from ' jsonwebtoken'
const { sign } = jwt

class sampleClass {

   static func(user) {
      return sign(
            {
                _id: user._id,
                name: user.name,
            },
            'sample key',
            {
                expiresIn: '7d',
            },
      )
   }

}

回答1:


Could you try something:

  1. Create a folder
  2. Do npm init
  3. Create a file app.js
  4. install json web token npm i jsonwebtoken
  5. Go to package.json and add "type": "module"
  6. write in your app.js this here: import jwt from "jsonwebtoken"
  7. Execute it: node --experimental-modules app.js

Tell me then if you get an error




回答2:


Your gonna need to import it and then assign it like this

import jwt from 'jsonwebtoken';
const { sign, verify } = jwt;
const token = sign({"d":"dd"}, "secret", {expiresIn: 300})
console.log(token);
const verifycode = verify(token, "secret");
console.log(verifycode);


来源:https://stackoverflow.com/questions/64275668/es6-imports-for-jwt

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