首页 文章

MEAN - 问题变得单一:来自列表的id数据

提问于
浏览
0

**我试图从列表中获取单个: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,...}错误:{title:“Not Authenticated”,错误:} headers:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ} message:“http:// localhost:7777 / article / 5b0be8829f734a4e580a43c5:401 Unauthorized”的Http失败响应名称:“HttpErrorResponse “ok:false status:401 statusText:”Unauthorized“url:”http:// localhost:7777 / article / 5b0be8829f734a4e580a43c5“

1 回答

  • 0

    我认为你应该授权通过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令牌

相关问题