Route.post()需要一个回调函数但得到一个[对象未定义]

时间:2018-04-24 00:15:32

标签: javascript node.js express

每当我运行npm start时,我都会收到此错误 我在索引文件中发布如下:

app.post('/api/actions',db.validateAction, db.createAction);

然后我在queries.js中有validationAction和createAction:

 21 function validateAction(req, res, next) {
 22 
 25   req.checkBody('dateDone', 'Invalid date').notEmpty();
 27   req.checkBody('completed', 'Invalid completed value').isBoolean();
 29 
 30   var errors = req.validationErrors();
 31 
 32   if (errors) {
 33     var response = { errors: [] };
 34     errors.forEach(function(err) {
 35       response.errors.push(err.msg);
 36     });
 37     res.statusCode = 400;
 38     return res.json(response);
 39   }
 40   return next();
 41 }

128 function createAction(req, res, next) { 
129   pool.connect(function(err,client,done) {
130 
131     if(err){
132       console.log("Not able to get connection "+ err + "\n");
133       res.status(400).send(err);
134     }
135 
136     var sql = 'INSERT INTO acts(dateDone, completed) VALUES($1,$2) RETURNING id';
137 
138     var data = [
141       req.body.dateDone,
143       req.body.completed,
145     ]
146 
147     client.query(sql, data, function(err, result) {
148 
149       if (err) {
150         console.error(err);
151         res.statusCode = 500;
152         return res.json({
153           errors: ['Failed to create action']
154         });
155       }
156 
157       // get new action
158       var newActionId = result.rows[0].id;
159       var sql = 'SELECT * FROM acts WHERE id = $1';
160 
161       client.query(sql, [newActionId], function(err, result) {
162 
163         if (err) {
164           console.error(err);
165           res.statusCode = 500;
166           return res.json({
167             errors: ['Could not retrieve action after create']
168           });
169         }
170 
171         console.log("Successfully created action");
172         // The request created a new resource object
173         res.status(201).json({
174           status: 'Success',
175           data: result.rows[0],
176           message: 'Created new action'
177         });
178       });
179     });
180   });
181 }

我的POST功能完美运行但现在一旦我尝试添加此验证,它就无法正常工作。我在路由处理程序之前注入了中间件(validateAction),因为我知道这是正确的方法,所以我不确定为什么这样做。

非常感谢任何指导。

0 个答案:

没有答案