javascript - 尽管映射正确,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);
解决方案
您的代码的问题是您尝试调用端点的方式。快速路线与查询字符串参数不匹配。
话虽如此,您对新闻端点的调用如下所示:
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
推荐阅读
- npm - 在 Linux Mint 18.3 中安装 npm
- sql-server - 如何在具有事务和回滚的单个存储过程中使用多个插入/更新/删除查询
- python - 在 Python 中操作目录的最简单方法?
- java - 在本地调试 Heroku Spring 启动应用程序?
- c++ - sprintf 和 char 数组 vs std::string
- c# - 如何从数据库制作这个可滚动的瓷砖列表的近似版本?
- cassandra - Cassandra:节点添加/删除是否需要所有集群节点都存在?
- ibm-cloud - 当 IBM Cloud 关闭时,IBM Cloud Availability Monitoring 是否工作?
- bash - 如何在 Travis CI 中触发失败?
- javascript - 如何在选择中添加选项并防止下拉框在选择标签的点击事件中消失