我在这里检查了很多答案,但没有任何帮助。无法找到护照设置的错误,以下是代码:
Server.js
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import bodyParser from "body-parser";
import dotenv from "dotenv";
import passport from "passport";
dotenv.config({ silent: true });
import passportFunction from "./config/passport";
passportFunction(passport);
import routes from "./routes";
mongoose.connect(process.env.DB);
mongoose.connection.once("open", () => {
console.log("Connected");
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.use("/api", routes);
app.listen(3000, () => {
console.log("App running on port 3000");
});

Passport.js
import passportJWT from "passport-jwt";
var ExtractJwt = passportJWT.ExtractJwt;
var JwtStrategy = passportJWT.Strategy;
import User from "../models/user";
export default function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(
new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({ _id: jwt_payload.id }, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
})
);
}

我认为自从我使用ES6以来导入护照策略存在问题。在此之前,我使用过''要求...',但无法弄明白,我在这里找到了答案,如何导入和传递参数以实现功能,它没有显示任何错误但不起作用..
我像router.post('/url', passport.authenticate('jwt') ....
答案 0 :(得分:0)
如果您遇到问题,这是解决方案,我从passport-jwt docs复制了策略,但由于这条线路它没有工作:
background-position
必须是User.findOne({ _id: jwt_payload.id }, function(err, user)...