@z0ddak
Мордор напоминает о себе

Как отследить ошибку запроса CRUD :: VUE + EXPRESS?

При включении всех контроллеров (tokenController.verifyToken, tokenController.isAdmin, crudController.crudUpdate) в проверку запроса - в data возвращается undefined
5d3a907aab6e6311435273.png

При отключении проверки токена и роли - запрос выполняется без ошибок:
5d3a90ad329b3547097866.png

Никак не могу отследить конфликтную точку. Привожу код:

= Фронтенд =
updateActive(id, key, model, address, ip, port, pass, status) {

                let data = {
                    headers: {'Authorization' : `Bearer ${this.token}`},
                    id: id,
                    key: key,
                    model: model,
                    address: address,
                    ip: ip,
                    port: port,
                    pass: pass,
                    status: status
                };
                this.$http.put('/product/' + id, data)
                    .then(response => {
                        const answer = response.data[1];
                    })
                    .catch(e => {
                        console.log(e);
                    });
}

= Бэкенд =
tokenController.verifyToken
verifyToken = (req, res, next) => {

    let token = req.headers['authorization'];
   console.log(token);

    if (!token) {

        let answer = {};
        answer.auth = false;
        answer.state = 'error';
        answer.text = 'No token provided.';
        return res.send(answer);
    }

    if (token.startsWith('Bearer ')) {

        let cleartoken = token.slice(7, token.length).trimLeft();
        jwt.verify(cleartoken, config.SECRET, (err, decoded) => {

            if (err) {

                let answer = {};
                answer.auth = false;
                answer.state = 'error';
                answer.text = 'Fail to Authentication. Error -> ' + err;
                return res.send(answer);
            } else {

                console.log('>>>> SUCCESS TOKEN >>>>');
                req.userId = decoded.id;
                next();
            }
        });
    } else {

        let answer = {};
        answer.auth = false;
        answer.state = 'error';
        answer.text = 'Bearer in token invalid!';
        return res.send(answer);
    }
};

tokenController.isAdmin
isAdmin = (req, res, next) => {

    User.findOne({_id: req.userId})
        .exec((err, user) => {

            if (err) {

                if (err.kind === 'ObjectId') {

                    let answer = {};
                    answer.state = 'error';
                    answer.text = 'User not found with Jabber/Telegram: ' + req.body.email;
                    return res.send(answer);
                }
                let answer = {};
                answer.state = 'error';
                answer.text = 'Error retrieving User with Jabber/Telegram: ' + req.body.email;
                return res.send(answer);
            }

            Role.find({

                '_id': {$in: user.roles}
            }, (err, roles) => {

                if (err) {

                    let answer = {};
                    answer.state = 'error';
                    answer.text = 'Error -> ' + err;
                    return res.send(answer);
                }

                for (let i = 0; i < roles.length; i++) {

                    if (roles[i].name.toUpperCase() === "ADMIN") {

                        console.log('>>>> SUCCESS ROLE >>>>');
                        return next();
                    }
                }
                let answer = {};
                answer.state = 'error';
                answer.text = 'Require Admin Role!';
                return res.send(answer);
            });
        });
};

crudController.crudUpdate
crudUpdate = (req, res) => {

    Product.findOneAndUpdate({_id: req.params.productId}, {

        key: req.body.key,
        model: req.body.model,
        address: req.body.address,
        ip: req.body.ip,
        port: req.body.port,
        pass: req.body.pass,
        status: req.body.status
    }, {new: true})
        .then(product => {

            if (!product) {

                let answer = {};
                answer.state = 'error';
                answer.text = 'Product not found with id' + req.params.productId;
                return res.send(answer);
            }
            let answer = {};
            answer.state = 'success';
            answer.text = req.body.model + ' successfully update to the database!';
            
            let newarray = [].concat(product, answer);

            console.log('>>>> SUCCESS UPDATE >>>>');
            return res.send(newarray);
        })
        .catch(err => {

            if (err.kind === 'ObjectId') {

                let answer = {};
                answer.state = 'error';
                answer.text = 'Product not found with id  ' + req.params.productId;
                return res.send(answer);
            }
            let answer = {};
            answer.state = 'error';
            answer.text = 'Error updating product with id  ' + req.params.productId;
            return res.send(answer);
        });
};


>> ответ сервера <<
5d3a9c9dcb561526170636.png
  • Вопрос задан
  • 108 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы