gpt4 book ai didi

javascript - bExpress bodyparser 未正确配置

转载 作者:行者123 更新时间:2023-12-01 00:31:22 25 4
gpt4 key购买 nike

我有一个 server.js 文件,其中有一个训练器路线

它用于在express中创建一些路由,但是每当我运行该程序时,它都会给我一个类型错误

firstName: req.body.firstName,                       ^

TypeError: Cannot read property 'body' of undefined

这是我的整个 server.js 文件。我已经为express配置了正确的bodyparsers,但它仍然给我同样的错误

服务器.js

const express = require('express');
const properties = require('./config/properties');
const db = require('./config/database');
const app = express();
const bodyParser = require('body-parser');
const log = require('morgan')('dev');
const cors = require('cors');


// call the database connectivity function
db();




//configure middleware
app.use(log);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


//parsers
const router = express.Router();

//routes
const trainerRoutes = require('./api/trainers/trainer.routes');



//configure routes
app.use('/api', router);

trainerRoutes(router);


app.listen(properties.PORT, (req, res)=>{
console.log(`Server running on ${properties.PORT} port`)
});

为什么会出现这个问题?

编辑:

这是发生错误的函数,位于 trainer.controller.js 文件中:

exports.updateTrainer = function(req, res, next) {
const trainer = {
firstName: req.body.firstName,
lastName: req.body.lastName,
biography: req.body.description,
certificates: req.body.certificates
};
Trainer.update({_id: req.params.id}, trainer, function(err, trainer) {
if(err) {
res.json({
error : err
//should make a log message here
})
}
res.json({
message : "Trainer updated successfully"
})
})
};

trainer.routes.js 文件

module.exports = function(router) {
router.post('/create', Trainer.createTrainer);
router.get('/get', Trainer.getAllTrainers);
router.get('/get/:name', Trainer.getTrainer);
router.put('/update/:id', Trainer.updateTrainer());
router.delete('/remove/:id', Trainer.removeHero());
};

最佳答案

我认为这条线

app.use('/api', router);

应该是

app.use('/api', trainerRoutes);

这行需要删除:

trainerRoutes(router);

你的 trainer.routes.js 应该是这样的:

const express = require('express');
const router = express.Router();

router.post('/create', Trainer.createTrainer);
router.get('/get', Trainer.getAllTrainers);
router.get('/get/:name', Trainer.getTrainer);
router.put('/update/:id', Trainer.updateTrainer);
router.delete('/remove/:id', Trainer.removeHero);

module.exports = router;

关于javascript - bExpress bodyparser 未正确配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58499857/

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