使用 NodeJS 和 ExpressJS 的基于令牌的身份验证护照的 运行 代码中的问题

Problem In running code for Token-based authentication-passport using NodeJS & ExpressJS

app.js

const express = require('express');
const path = require('path');
const logger = require('morgan');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

app.use('/dishes', dishRouter);
app.use('/dishes/:dishId', dishRouter);

module.exports = app;

authenticate.js

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('./models/user');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwt= require('jsonwebtoken');
const config = require('./config.js');

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

exports.local = passport.use(new LocalStrategy(User.authenticate()));

exports.getToken=function(user){
  return jwt.sign(user, config.secretKey,
    {expiresIn: 3600});
};

const opts = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: config.secretKey
};

exports.jwtPassport = passport.use(new JwtStrategy(opts,
  (jwt_payload, done)=>{
    User.findOne({_id:jwt_payload._id}, (err, user)=>{
      if(err){
        return done(err, false);//(optional params)callback that passport will pass your startegy here
      }
      else if(user) {
        return done(null, user);
      }
      else{
        return done(null, false);//if we want we can create a new user
      }
    });
  }));

exports.verifyUser = passport.authenticate('jwt', { session: false });

config.js

module.exports={
    'secretKey':'12345-67890-09876-54321',
    'mongoUrl':'mongodb://localhost:27017/conFusion'
}

dishRouter.js

const express = require('express');
const bodyParser = require('body-parser');
const authenticate = ('../authenticate');//higher level folder
const Dishes = require('../models/dishes');
const dishRouter = express.Router();

dishRouter.use(bodyParser.json());
dishRouter.route('/')
.get((req,res,next) => {
  //performing find operation 
  Dishes.find({}).then((dishes)=>{
    res.statusCode = 200;
    res.setHeader('Content-Type','application/json');
    //take a input as a json string & send it back to the client(json response)
    res.json(dishes);
  },(err)=>next(err)).catch((err)=>next(err));
})
.post(authenticate.verifyUser, (req, res, next) => {
  Dishes.create(req.body).then((dishes)=>{
    console.log('dish created...',dishes);
    res.setHeader('Content-Type','application/json');
    res.json(dishes);
  },(err)=>next(err)).catch((err)=>next(err));
})
.put(authenticate.verifyUser,(req, res, next) => {
  res.statusCode = 403;
  res.end('PUT operation not supported on /dishes');
})
.delete(authenticate.verifyUser,(req, res, next) => {
  Dishes.remove({}).then((resp)=>{
    res.statusCode = 200;
    res.setHeader('Content-Type','application/json');
    //take a input as a json string & send it back to the client(json response)
    res.json(resp);
  },(err)=>next(err)).catch((err)=>next(err));
});

// Other routes

module.exports = dishRouter;

虽然运行代码我得到了以下错误

While running this code I got Error: Route.post() requires a callback function but got a [object Undefined] at Route. [as post] (D:\EDUCATION\nodejs\node-express generator\conFusionServer\node_modules[4mexpress[24m\lib\router\route.js:202:15) at Object. (D:\EDUCATION\nodejs\node-express generator\conFusionServer\routes\dishRouter.js:21:4) and Error app.js:28 th line I am unable fix this error anyone can help me to fix this error

dishRouter.js 中缺少 require;第 4 行

修复:

const authenticate = require('../authenticate');