【问题标题】:MEAN - issue getting single :id data from listMEAN - 从列表中获取单个 :id 数据的问题
【发布时间】:2018-11-07 04:12:57
【问题描述】:

**我正在尝试从列表中获取单个 :id 但它没有按预期返回数据... **

GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> 我的获取请求响应

我的 api ===>

var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var User = require('../models/User')
var Article = require('../models/Article');


router.get('/', function (req, res, next) {
    Article.find()
        .populate('user')
        .exec(function (err, articles) {
            if (err) {
                return res.status(500).json({
                    title: 'An error occured getting articles',
                    error: err
                });
            }
            res.status(200).json({
                message: "Success",
                obj: articles
            });
        });
});

//I'm having issue with this route below
//I'm having issue with this route below

router.get('/article/:articleId', function (req, res, next) {
    // Check if the blog id is found in database
    // var decoded = jwt.decode(req.query.token);
    Article.findById(req.params.articleId, function (err, article) {
            // if the ID is not found or invalid, return err
            if (err) {
                return res.status(500).json({
                    title: 'An error occured',
                    error: err
                });
            }
            // if the article was not found anyways
            if (!article) {
                return res.status(500).json({
                    title: 'Article not found',
                    error: { message: 'Article was not found!' }
                });
            }
                res.status(200).json({
                    message: 'successful :id',
                    obj: article
                });
        });
});



//ROAD-BLOCK => { (checking if you're authenticated(true))}
router.use('/', function (req, res, next) {
    jwt.verify(req.query.token, 'secret', function (err, decoded) {
        if (err) {
            return res.status(401).json({
                title: 'Not Authenticated',
                error: err
            });
        }
        next();
    })
});


router.post('/', function (req, res, next) {
    var decoded = jwt.decode(req.query.token);
    User.findById(decoded.user._id, function (err, user) {
        if (err) {
            return res.sendStatus(500).json({
                title: 'An error occured',
                error: err
            });
        }
        var article = new Article({
            title: req.body.title,
            description: req.body.description,
            body: req.body.body,
            username: user.username,
            userId: user._id,
            favoritesCount: 33,
            articleId: req.body._id 
            // comments: 'bla'
        });

        article.save(function (err, result) {
            if (err) {
                return res.status(500).json({
                    title: 'An error occured when saving',
                    error: err
                });
            }
            user.articles.push(result);
            console.log(result);
            user.save();
            res.status(201).json({
                message: 'Article saved succesfully',
                obj: result
            });
        });
    });
});

// Updating an article // /:id
router.patch('/:id', function (req, res, next) {
    var decoded = jwt.decode(req.query.token);
    Article.findById(req.params.id, function (err, article) {
        if (err) {
            return res.status(500).json({
                title: 'An error occured',
                error: err
            });
        }
        if (!article) {
            return res.status(500).json({
                title: 'Article not found',
                error: { message: 'Article was not found!' }
            });
        }
        if (article.user != decoded.user._id) {
            return res.status(401).json({
                title: 'Not Authenticated',
                error: {
                    message: 'Users do not match'
                }
            });
        }
        article.title = req.body.title,
            article.description = req.body.description,
            article.body = req.body.body,
            article.favoritesCount = 33,
            // article.tags = req.body.tags,
            article.save(function (err, result) {
                if (err) {
                    return res.status(500).json({
                        title: 'An error occured',
                        error: err
                    });
                }
                res.status(200).json({
                    message: 'updated succesfully',
                    obj: result
                });
            });
    });
});

router.delete('/:id', function (req, res, next) {
    var decoded = jwt.decode(req.query.token);
    Article.findById(req.params.id, function (err, article) {
        if (err) {
            return res.status(500).json({
                title: 'An error occured',
                error: err
            });
        }
        if (!article) {
            return res.status(500).json({
                title: 'Article not found',
                error: { message: 'Article was not found!' }
            });
        }
        if (article.user != decoded.user._id) {
            return res.status(401).json({
                title: 'Not Authenticated',
                error: {
                    message: 'Users do not match'
                }
            });
        }
        article.remove(function (err, result) {
            if (err) {
                return res.status(500).json({
                    title: 'An error occured',
                    error: err
                });
            }
            res.status(200).json({
                message: 'deleted succesfully',
                obj: result
            });
        });
    });
})

module.exports = router;

其他路线正在按预期工作......

这是我的服务,它连接到我前端的路由 api...

  ngOnInit() {
    this.getArticleDetail(this.activatedRoute.snapshot.params['articleId']);
  }

//   ngOnInit() {
//     this.articleService.getArticle(this.article)
//         .subscribe(article => this.article = article);
// }

  getArticleDetail(articleId) {
    this.http.get('/article/' + articleId).subscribe(
      data => {
        this.article = data;
      }
    );
  }

浏览器控制台中的错误响应 ===>

HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:7777/article/5b0be8829f734a4e580a43c5", ok: false, …} 错误 : {标题:“未验证”,错误:{…}} 标题 : HttpHeaders {normalizedNames: Map(0),lazyUpdate:null,lazyInit:ƒ} 信息 : “http://localhost:7777/article/5b0be8829f734a4e580a43c5 的 Http 失败响应:401 Unauthorized” 姓名 : “HttpError 响应” 好的 : 错误的 状态 : 401 状态文本 : “未经授权” 网址 : "http://localhost:7777/article/5b0be8829f734a4e580a43c5"

【问题讨论】:

  • 您没有从前端传递身份验证令牌
  • 我现在...感谢人

标签: javascript angular mongodb mongoose mean


【解决方案1】:

我认为您应该授权通过 id 获取特定项目。

router.use('/', function (req, res, next) {
jwt.verify(req.query.token, 'secret', function (err, decoded) {
    if (err) {
        return res.status(401).json({
            title: 'Not Authenticated',
            error: err
        });
    }
    next();
})

});

你有授权中间件,所以每个请求都应该被授权。

尝试从您的角度服务发送 jwt 令牌

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多