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

时间:2019-03-05 05:10:09

标签: node.js express model-view-controller routes middleware

我正在尝试将数据从控制器传递到路由。

我想将状态代码从控制器更改为路由。假设控制器状态为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)

2 个答案:

答案 0 :(得分: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 
            }
         })
    });

答案 1 :(得分: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"});
   })
});