我是nodejs的新手,我正在尝试使用jwt和passport进行安全路由,这很好,但是当我尝试使用猫鼬验证数据库中的某些信息并返回结果时,出现此错误“无法设置标头发送之后”
这是生成错误的代码(res.status(404).json(errors))
router.get(
'/',
passport.authenticate('jwt', { session: false }),
(req, res) => {
const errors = {};
Profile.findOne({ user: req.user.id })
.then(profile => {
if (!profile) {
errors.noprofile = 'There is no profile for this user';
return res.status(404).json(errors);
}
res.json(profile);
})
.catch(err => console.log(err));
}
);
这是个人资料模型shcema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
handel: {
type: String,
require: true,
max: 40
},
company: {
type: String,
},
webSite: {
type: String,
},
location: {
type: String,
},
});
module.exports = Profile = mongoose.model('profile', ProfileSchema);
这是我的服务器
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const profile = require('./routes/api/profile');
const app = express();
// passport
app.use(passport.initialize());
// passport config
require('./config/passport')(passport);
// body Parser middleware
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
//DB config and connection
const db=require('./config/keys').mongoURI;
mongoose.connect(db, { useNewUrlParser: true })
.then(() => console.log("connected"))
.catch(err => console.log(err))
app.use('/api/profile',profile);
const port=process.env.PORT ||5000
app.listen(port,() => console.log('works'))
这是我的护照配置
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model('user');
const keys = require('./keys');
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretKey;
module.exports = passport => {
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id)
.then(user => {
if(user){
done(null, user);
}
done(null, false);
}).catch(err => console.log(err));
}))
}