我使用
每次无法提供令牌时,我都会收到未经授权的响应。我想将其更改为漂亮的消息。 passport.js
我该如何将“未授权”消息美化,并更改为通俗易懂的信息(“您无法获取详细信息”)?
passport
创建了一个Node
项目。当我没有将令牌作为标头提供时,它会返回Unauthorized
。我该如何将此消息更改为漂亮的Sorry invalid credentials
?每次无法提供令牌时,我都会收到未经授权的响应。我想将其更改为漂亮的消息。 passport.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
var User = require('../models/user'); // get the mongoose model
const keys = require('../config/keys');
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;
module.exports = passport => {
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id)
.then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err))
})
);
};
用户路由.js
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');
const setting=require("../validation/settings");
const User = require('../models/user');
// *** GET *** /api/users/all *** Retrieve all users' basic details ***
router.get("/", passport.authenticate('jwt', {session: false}), function (req, res)
{
var token = getToken(req.headers);
console.log('the token: ' + token);
User.find()
.select('fname lname email avatar contact_no role')
.where('is_deleted').equals('false')
.exec()
.then(docs => {
return res.send(setting.status("User details retrieval successfully",false, "User details retrieval successfully", docs))
//res.status(200).json(setting.status(validation.SHOW,true,"User details retrieval successfully.",docs))
.catch(err => {
return res.send(setting.status("Error in retrieving user details",false, "Error may token", err))
});
});
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
module.exports = router;
我该如何将“未授权”消息美化,并更改为通俗易懂的信息(“您无法获取详细信息”)?