Route.post()需要回调函数,但得到了[object String]

时间:2018-09-19 07:41:06

标签: javascript node.js express

我正在尝试使用并更改MDN节点/快速教程制作词汇应用程序。

MDN教程效果很好,但是我的却不起作用。

以下是错误:

Error: Route.post() requires a callback function but got a [object String]
    at Route.(anonymous function) [as post] (d:\web-projects\vocastudy\node_modules\express\lib\router\route.js:202:15)
    at Function.proto.(anonymous function) [as post] (d:\web-projects\vocastudy\node_modules\express\lib\router\index.js:510:19)
    at Object.<anonymous> (d:\web-projects\vocastudy\routes\catalog.js:9:8)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (d:\web-projects\vocastudy\app.js:9:21)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)

还有app.js:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var catalogRouter = require('./routes/catalog');

var app = express();

// Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/vocastudy';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/catalog', catalogRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

我的路线catalog.js:

var express = require('express');
var router = express.Router();
var vocabulary_controller = require('../controllers/vocabularyController');

// GET request for creating a Word. NOTE This must come before routes tha display Word (uses id).
router.get('/create', vocabulary_controller.create_get);

/* POST create page */
router.post('/create', vocabulary_controller.create_post);

/* GET home page. */
router.get('/', vocabulary_controller.list);

/* GET detail page */
router.get('/:id', vocabulary_controller.detail);

module.exports = router;

和控制器vocabulary.js:

exports.create_post = [

  // Validate fields
  body('word').isLength({ min: 1 }).trim().withMessage('word must be specified'),
  body('meaning').isLength({ min: 1 }).trim().withMessage('meaning must be specified'),
  body('reference').isLength({ min: 1 }).trim().withMessage('reference must be specified'), 

  // Sanitize (trim and escape) the fields
  sanitizeBody('word').trim().escape(),
  sanitizeBody('meaning').trim().escape(),
  sanitizeBody('reference').trim(),escape(),

  // Process request after validation and sanitization
  (req, res, next) => {

    // Extract the validation errors from a request.
    const errors = validationResult(req);

    // Create vocabulary object with escaped and trimmed data.
    if(!errors.isEmpty()) {
      // There are errors.
      res.render('create', { title: 'Create Word', word: req.body, errors: errors.array() });
      return;
    } else {
      // Data from form is valid.

      // Create a Vocabulary object with escaped and trimmed data.
      var vocabulary = new Vocabulary({
        word: req.body.word,
        meaning: req.body.meaning,
        reference: req.body.reference
      });

      vocabulary.save(function(err) {
        if(err) { return next(err); };
        // Successful - redirect to new word record.
        res.redirect(vocabulary.url);
      });
    };
  }
];

我认为创建后置控制器是数组,因此出现错误,但它在MDN的教程版本中完全适用。我找不到我的问题。 为什么我得到route.post错误? 注意,mdn的教程也使用数组。

1 个答案:

答案 0 :(得分:0)

似乎在Express中,app.post()接受的参数可以是回调的数组,但是router.post()仅接受函数作为回调。尝试将数组直接提供给快速应用而不是路由器,或者按照@TimothyLee的建议,使用spread syntax将数组变成router.post()函数的各个参数。