文件移动到控制器文件时,该api无法正常工作。从邮递员点击api会导致无休止的请求"/>
当我将快递代码从路由文件移动到控制器文件时,该api无法正常工作。从邮递员点击api会导致无休止的请求
[当我在authorRouter.js文件中编写了post and get函数时,该api正在工作,但是当我将这些函数移到controllers文件夹中的authorController.js文件中时,该api停止了工作。当我从邮递员那里调用api时,它将导致永无休止的请求。我以前是这样从路由器文件调用控制器功能的:
.post(controller.post) .get(controller.get)
但是它给我一个错误“ Route.get()需要一个回调函数,但是得到了一个[对象未定义]”,因此我如下编辑了路由器文件:
authorRouter.js文件
const express = require('express'); const authorController = require('../controllers/authorController'); function routes(Author){ const authorRouter = express.Router(); const controller = authorController(Author); authorRouter.route('/author') .post( function(req, res){ controller.post }) .get( function(req,res){ controller.get } ); // .post((req,res)=>{ // const author = new Author(req.body); // author.save(); // return res.status(201).json(author); // }) // .get((req,res)=>{ // const query = {}; // if(req.query.name){ // query.name = req.query.name; // } // Author.find(query,(err,authors)=>{ // if(err){ // return res.send(err); // } // return res.json(authors); // }); // }); authorRouter.use('/author/:authorId',(req,res,next)=>{ Author.findById(req.params.authorId,(err,author)=>{ if(err){ return res.send(err); } if(author){ req.author =author; return next(); } return res.sendStatus(404); }); }); authorRouter.route('/author/:authorId') .get((req,res)=>{ res.json(req.author); }) .put((req,res)=>{ const {author} =req; author.name = req.body.name; author.book = req.body.book; author.age = req.body.age; req.author.save((err)=>{ if(err){ return res.send(err); } return res.json(author); }) }) .patch((req,res)=>{ const { author} =req; if (req.body._id){ delete req.body._id; } Object.entries(req.body).forEach(item=>{ const key = item[0]; const value = item[1]; author[key]= value; }); req.author.save((err)=>{ if(err){ return res.send(err); } return res.json(author); }); }) .delete((req,res)=>{ req.authorId.remove((err)=>{ if(err){ return res.send(err); } return res.sendStatus(204); }) }); return authorRouter; } module.exports= routes;
authorController.js文件
function authorController(Author){ function post(req,res){ const author = new Author(req.body); author.save(); return res.status(201).json(author); } function get(req,res) { const query = {}; if(req.query.name){ query.name = req.query.name; } Author.find(query,(err,authors)=>{ if(err){ return res.send(err); } return res.json(authors); }); } return(post, get ); } module.exports = authorController;
为什么会这样?
[当我在authorRouter.js文件中编写post and get函数时,该api正在工作,但是当我将这些函数移至controllers文件夹中的authorController.js文件中时,该api已停止...]
您可以试试吗?>
.post(function (req, res) {
controller.post(req, res);
})
回答如下:.post(function (req, res) {
controller.post(req, res);
})
更多推荐
当我将快递代码从路由文件移动到控制器文件时,该api无法正常工作。从邮递员点击api会导致无休止的请求
本文发布于:2024-05-07 05:49:06,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
- 上一篇: Lidar
- 下一篇: 【转发】淘宝网架构分享总结
发布评论