Route.post()需要回调函数,但是在编译nodeJS时得到了[object Undefined]

时间:2019-08-27 11:40:17

标签: node.js express

我正在遵循API基础教程,每当我运行项目时,都会收到错误Error: Route.post() requires a callback function but got a [object Undefined] 这是我的路线文件

module.exports = function (app) {
    var todoList = require('../controllers/todoListController');
    app.route('/tasks')
        .get(todoList.list_all_tasks)
        .post(todoList.create_a_task);

    app.route('/task/:taskId')
        .get(todoList.read_a_task)
        .put(todoList.update_a_task)
        .delete(todoList.delete_a_task);
};

这是我的server.js文件

var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000,
    mongoose = require('mongoose'),
    Task = require('./api/models/todoListModel'), //created model loading here
    bodyParser = require('body-parser');

// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb');


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


var routes = require('./api/routes/todoListRoutes'); //importing route
routes(app); //register the route


app.listen(port);


console.log('todo list RESTfaul API server started on: ' + port);

即使我尝试将回调函数传递给post方法,但仍然无法编译

2 个答案:

答案 0 :(得分:1)

您需要在您的post方法中插入回调

module.exports = function (app) {
    var todoList = require('../controllers/todoListController');
    app.route('/tasks')
        .get(todoList.list_all_tasks)
        .post(todoList.create_a_task, function(req, res) {//smth});
};

答案 1 :(得分:1)

您可以尝试这样做。

...

app.route('/tasks')
   .get((req, res) => { return todoList.list_all_tasks( req, res) }),
   .post((req, res) => { return todoList.create_a_task(req, res) })