与Jsonwebtokens的Promises vs Async

Nol*_*vis 5 javascript asynchronous promise json-web-token

我完成了一个Node app教程并回过头来用async/await重写代码,以便更好地了解它是如何完成的.但是我有一个路由处理程序,如果不使用promises,我就无法做到:

getProfile: function(id){
    return new Promise(function(resolve, reject){
        Profile.findById(id, function(err, profile){
            if (err){
                reject(err)
                return
            }

            resolve(profile.summary())
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

我改写为:

getProfile: async (req, res, next) => {
    const profileId = req.params.id;
    const profile = await Profile.findById(profileId);
    res.status(200).json(profile)
}
Run Code Online (Sandbox Code Playgroud)

编辑2:好的我也意识到我改写了:

create: function(params){
    return new Promise(function(resolve, reject){

        var password = params.password
        params['password'] = bcrypt.hashSync(password, 10)

        Profile.create(params, function(err, profile){
            if (err){
                reject(err)
                return
            }

            resolve(profile.summary())
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

newProfile: async (params, res, next) => {
    const newProfile = new Profile(params);
    const password = params.password
    params['password'] = bcrypt.hashSync(password, 10)
    const profile = await newProfile.save();
    return profile.summary()
},
Run Code Online (Sandbox Code Playgroud)

这很可能导致jsonwebtokens的问题:<

我遇到问题的API端点使用jsonwebtokens:

var token = req.session.token
    utils.JWT.verify(token, process.env.TOKEN_SECRET)
    .then(function(decode){
        return controllers.profile.getProfile(decode.id)
    })
    .then(function(profile){
        res.json({
            confirmation: 'success',
            profile: profile
        })
    })
    .catch(function(err){
        res.json({
            confirmation: 'fail',
            message: 'Invalid Token'
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

异步代码适用于/ profile路由的GET和POST请求,但在API catch块中不断获取"Invalid Token"消息.我是承诺和异步代码的新手,所以我确定我现在很多都不理解.

所以我的问题是如何重写承诺以正确的格式传递配置文件对象?

完整档案:

控制器/ ProfileController.js

var Profile = require('../models/Profile')
var Album = require('../models/Album')
var Promise = require('bluebird')
var bcrypt = require('bcryptjs')

module.exports = {
    index: async (req, res, next) => {
        const profiles = await Profile.find({});
        const summaries = []
        profiles.forEach(function(profile){
            summaries.push(profile.summary())
        })
        res.status(200).json(summaries)
    },

    newProfile: async (params, res, next) => {
        const newProfile = new Profile(params);
        const password = params.password
        params['password'] = bcrypt.hashSync(password, 10)
        const profile = await newProfile.save();
        return profile.summary()
    },

    getProfile: function(id){
        return new Promise(function(resolve, reject){
            Profile.findById(id, function(err, profile){
                if (err){
                    reject(err)
                    return
                }

                resolve(profile.summary())
            })
        })
    },

    updateProfile: async (req, res, next) => {
        const { profileId } = req.params;
        const newProfile = req.body;
        const result = await Profile.findByIdAndUpdate(profileId, newProfile);
        res.status(200).json({success: true})
    },

    getProfileAlbums: async (req, res, next) => {
        const profileId = req.params.id;
        const profile = await Profile.findById(profileId);
    },

    newProfileAlbum: async (req, res, next) => {
        const newAlbum = new Album(req.body);
        console.log('newAlbum', newAlbum)
    }

}
Run Code Online (Sandbox Code Playgroud)

路线/ profile.js:

var express = require('express');
const router = require('express-promise-router')();

const ProfileController = require('../controllers/ProfileController')

router.route('/')
    .get(ProfileController.index)
    .post(ProfileController.newProfile);

router.route('/:id')
    .get(ProfileController.getProfile)
    .patch(ProfileController.updateProfile);

router.route('/:id/album')
    .get(ProfileController.getProfileAlbums)
    .post(ProfileController.newProfileAlbum);

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

路线/ account.js:

var express = require('express')
var router = express.Router()
var controllers = require('../controllers')
var bcrypt = require('bcryptjs')
var utils = require('../utils')

router.get('/:action', function(req, res, next){
    var action = req.params.action

    if (action == 'logout'){
        req.session.reset()
        res.json({
            confirmation: 'success'
        })
    }

    if (action == 'currentuser'){
        if (req.session == null) {
            res.json({
                confirmation: 'success',
                message: 'user not logged in'
            })

            return
        }

        if (req.session.token == null) {
            res.json({
                confirmation: 'success',
                message: 'user not logged in'
            })

            return
        }

        var token = req.session.token
        utils.JWT.verify(token, process.env.TOKEN_SECRET)
        .then(function(decode){
            return controllers.profile.getProfile(decode.id)
        })
        .then(function(profile){
            res.json({
                confirmation: 'success',
                profile: profile
            })
        })
        .catch(function(err){
            res.json({
                confirmation: 'fail',
                message: 'Invalid Token'
            })
        })
    }
})

router.post('/register', function(req, res, next){
    var credentials = req.body

    controllers.profile
    .newProfile(credentials)
    .then(function(profile){
        var token = utils.JWT.sign({id: profile.id}, process.env.TOKEN_SECRET)
        req.session.token = token
        res.json({
            confirmation: 'success',
            profile: profile,
            token: token
        })
    })
    .catch(function(err){
        res.json({
            confirmation: 'fail',
            message: err.message || err
        })
    })
})

router.post('/login', function(req, res, next){

    var credentials = req.body
    controllers.profile
    .find({userName: credentials.userName}, true)
    .then(function(profiles){
        if (profiles.length == 0){
            res.json({
                confirmation: 'fail',
                message: 'Profile not found'
            })
            return
        }
        var profile = profiles[0]

        var passwordCorrect = bcrypt.compareSync(credentials.password, profile.password)
        if (passwordCorrect == false){
            res.json({
                confirmation: 'fail',
                message: 'Incorrect password'
            })

            return
        }

        var token = utils.JWT.sign({id: profile._id}, process.env.TOKEN_SECRET)
        req.session.token = token

        res.json({
            confirmation: 'success',
            profile: profile.summary(),
            token: token
        })
    })
    .catch(function(err){
        res.json({
            confirmation: 'fail',
            message: err
        })
    })
})

module.exports = router
Run Code Online (Sandbox Code Playgroud)

utils的/ JWT.js:

var jwt = require('jsonwebtoken')
var Promise = require('bluebird')

module.exports = {

    sign: function(obj, secret){
        return jwt.sign(obj, secret)
    },

    verify: function(token, secret){

        return new Promise(function(resolve, reject){
            jwt.verify(token, secret, function(err, decode){
                if (err){
                    reject(err)
                    return
                }

                resolve(decode)
            })
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

nat*_*tan 5

validate.js:

async verifyToken(jwt,token,key){
   if(!token) return {};
   return new Promise((resolve,reject) =>
      jwt.verify(token,key,(err,decoded) => err ? reject({}) : 
                                                  resolve(decoded))
   );
}


auth.js:

const jwt = require('jsonwebtoken');
const {verifyToken} = require('../functions/validate');
const TOKEN_KEY = "abrakadabra";

const token = await verifyToken(
     jwt, req.session.token, TOKEN_KEY
).catch(err => {}) || {};
// || {} - need if decoded is undefined

console.log(token.id);
Run Code Online (Sandbox Code Playgroud)


ske*_*tor 0

Profile.findById不返回承诺。当它最初起作用时,您正在使用回调。包装Profile.findById在一个承诺中,然后在包装的函数上使用await关键字。