首页 > 解决方案 > 尽管映射正确,Node/ Express Rest API 仍继续进入相同的控制器功能

问题描述

我正在编写一个节点/快速休息 api。

点击, http://localhost:5000/api/news

http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80

两者都给了我所有的新闻对象,因为它为两个 url 输入了相同的 .getNews 函数。

我的控制器:

const NewsController = {};
const News = require('../models/news.model');

// This implementation of getNews is using Promises
NewsController.getNews = function(req, res) {

  console.log('Inside getNews');
  sendResponse = function(arg) {
    res.json(arg);
  }

  const allnews = News.find({}, function(err, ns) {
    sendResponse(ns);
  });


};


// ES6 style
NewsController.getSingleNews = async (req, res) => {

  console.log("Inside getSingleNews");
  const news = await News.findById(req.params.id);
  res.json[news];
};


NewsController.createNews = async (req, res) => {
  const news = new News(req.body);
  await news.save();

  res.json[{
    'status': 'item saved successfully'
  }];
};

NewsController.deleteNews = async (req, res) => {
  await News.findByIdAndRemove(req.params.id);
  res.json[{
    'status': 'item deleted successfully'
  }]
};


module.exports = NewsController;

我的 routes.js (我在 /api 使用路由器。所以 app.js 有 // 使用路由器

app.use('/api', newsRoutes);

)

const express = require('express');
const router = express.Router();
var newsController = require('../controllers/NewsController')

router.get('/news', newsController.getNews);
router.get('/news/:id', newsController.getSingleNews);
router.post('/news', newsController.createNews);
router.delete('news/:id', newsController.deleteNews);

module.exports = router;

我的模特

const mongoose = require('mongoose');


const { Schema } = mongoose;
const newsSchema = new Schema({
  title: { type: String, required: true },
  content: { type: String, required: true },
  author: { type: String },
  image: { type: String },
  source: { type: String }
});

module.exports = mongoose.model('news', newsSchema);

标签: javascriptnode.jsrestexpressmean-stack

解决方案


您的代码的问题是您尝试调用端点的方式。快速路线与查询字符串参数不匹配

话虽如此,您对新闻端点的调用如下所示:

http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80

应该看起来像这样:

http://localhost:5000/api/news/c5f69d56be40e3b56e55d80

这样id参数将被映射到getSingleNews控制器内的req.params.id属性。

作为您声明路线的方式的预期行为:

router.get('/news/:id', newsController.getSingleNews);

有关快速路线如何工作的更多信息,请查看此处的文档:https ://expressjs.com/en/guide/routing.html


推荐阅读