如何将数据从控制器传递到路由

问题描述 投票:0回答:2

我试图将数据从控制器传递到路由。

我想将状态代码从控制器更改为路由。如果在控制器状态200中,则将其从路径更改为400

要么

只需简单的打印问候或响应之后的路线

这是来自控制器文件的控制器 联系控制器。 JS

exports.index = function(req, res) {
  Contact.get(function(err, contacts) {
    if (err) {
      res.json({
        status: "error",
        message: err
      });
    }

    res.json({
      status: "success",
      message: "Contacts retrieved successfully",
      data: contacts
    });
  });
};

这是路由文件的路由 联系router.js

var contactController = require('./contactController');

// Contact routes
router.route('/contacts')
    .get(contactController.index)
node.js express model-view-controller routes middleware
2个回答
0
投票

按照本文使用快速路由器设计您的应用程序

https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4

像这样定义你的控制器

exports.index = function(req, res, next) {
  Contact.get(function(err, contacts) {
    if (err) {
      next(null,{
        status: "error",
        message: err
      });
    }

    next({
      status: "success",
      message: "Contacts retrieved successfully",
      data: contacts
    },null);
  });
};

像这样定义主应用程序文件

var contactController = require('./contactController');
    var router = express.Router();
    // apply the routes to our application
    // route middleware that will happen on every request
    router.use(function(req, res, next) {
        // continue doing what we were doing and go to the route
        next(); 
    });

    // about page route (http://localhost:8080/about)
    router.get('/contacts', function(req, res) {
        //here you can call your controller js method
        contactController.index(req,res, function(data, err){
            //change anything you want here and set into res.
            if(err){
              //change status and data
            }
            else{
               //change status and data 
            }
         })
    });

0
投票

不要在控制器中结束请求 - 响应周期,只需从控制器返回结果而不是结束周期。

const httperror = require('http-errors');

exports.index = async function(parameter) {
  Contact.get(function(err, contacts) {
    if (err) {
     throw new httperror(400, "Error occured!");
    }

    return {
       status: "success",
       message: "Contacts retrieved successfully",
       data: contacts
    }
  });
};

请求应从路由开始,响应应从路由发送

const contactController = require('./contactController');

router.get('/contacts', function (req, res, next) {
   contactController.index()
     .then(result => {
        res.json(result)
     }).catch((error) => {
        res.status(200).json({"Error":"Returned success code 200 even though error 
        occured"});
   })
});
© www.soinside.com 2019 - 2024. All rights reserved.