gpt4 book ai didi

javascript - Route.post() 需要一个回调函数,但得到一个 [object String]

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:40 25 4
gpt4 key购买 nike

我正在尝试使用和更改 MDN Node/express 教程来制作我的词汇应用程序。

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;

和 Controller 词汇.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);
});
};
}
];

我认为创建后 Controller 是数组,所以我得到了错误,但它在 MDN 的教程版本上完美运行。我找不到我的问题。为什么我收到route.post 错误?请注意,mdn 的教程也使用数组。

最佳答案

似乎在 Express 中,app.post()接受可以是回调数组的参数,但是 router.post()只接受函数作为回调。尝试将数组直接提供给 Express 应用程序而不是路由器,或者按照 @TimothyLee 建议,使用 spread syntax将数组转换为 router.post() 函数的单独参数。

关于javascript - Route.post() 需要一个回调函数,但得到一个 [object String],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52400652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com