简体   繁体   中英

error 500 internal server error express-jwt

I'm having trouble figuring out why postman keeps returning empty curly braces with 500 internal server error whenever in use Bearers token in authorization for POST 'http://localhost:3000/api/v1/products' isAdmin true. This is my jwt.js file

const { expressjwt: expressJwt } = require('express-jwt');

function authJwt() {
    const secret = process.env.secret
    const api = process.env.API_URL
    return expressJwt({
        secret,
        algorithms: ['HS256'],
        isRevoked: isRevoked
    }).unless({
        path: [
            { url: /\/api\/v1\/products(.*)/, methods: ['GET', 'OPTIONS'] },
            { url: /\/api\/v1\/categories(.*)/, methods: ['GET', 'OPTIONS'] },
            `${api}/users/login`,
            `${api}/users/register`,
        ]
    })
}

async function isRevoked(req, payload, done) {
    if(!payload.isAdmin) {
       done(null, true);
    }
 
   done(); 
};


module.exports = authJwt

Upon introducing this lines of codes, Postman returns authorization error even with the Bearers token. My good developers, come through for me here. I've been stuck for a whole week. My aim is the API should post the new product using isAdmin [true] bearer's token.

async function isRevoked(req, token) {
   
    if(!token.payload.isAdmin) {
        return true
    }
     return undefined;
}

The error-handler file



function errorHandler(err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    return res.status(401).json({message: 'The user is not authorized'})
  }

  if (err.name === 'ValidationError') {
    return res.status(401).json({message: err})
  }
  
  return res.status(500).json(err);
}


module.exports = errorHandler

  1. In your app.js use authJwt() instead of just authJwt

  2. use following

async function isRevoked(req, token){ if(.token.payload;isAdmin) { return true; } }

and comment out

async function isRevoked(req, payload, done) {
    if(!payload.isAdmin) {
       done(null, true);
    }
 
   done(); 
};

and comment out

async function isRevoked(req, token) {
   
    if(!token.payload.isAdmin) {
        return true
    }
     return undefined;
}

in your jwt.js

  1. Increase your token time from 1d to more days say 10d

  2. Get your fresh Token

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM