gpt4 book ai didi

javascript - 尽管映射正确,Node/Express Rest API 仍不断输入相同的 Controller 功能

转载 作者:行者123 更新时间:2023-12-03 00:08:57 25 4
gpt4 key购买 nike

我正在编写一个 Node/express Rest API。

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

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

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

我的 Controller :

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//use Router

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 Controller 内的 req.params.id 属性。

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

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

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

关于javascript - 尽管映射正确,Node/Express Rest API 仍不断输入相同的 Controller 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54833407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com