首页 > 解决方案 > 控制器 Express 中未定义的请求正文

问题描述

当我编写 console.log(req); 时,我的控制器出现问题;我有请求正文的所有内容,但是当我写 console.log(req.body); 是未定义的。我正在尝试使用 Next.js React 和 Express 编写我的作品集。

这是我的服务器 index.js:

const express = require('express');
const next = require('next');
const routes = require('../routes');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');


// SERVICE
const authService = require('./services/auth');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = routes.getRequestHandler(app);
const config = require('./config');

const portfolioRoutes = require('./routes/portfolio');

const secretData = [
{   id: '1',
    title: 'Secret Data',
    description: 'plans for build something !'
},
{   
    id: '2',
    title: 'Secret Data2',
    description: 'plans for build something2 !'
}
]


//MONGODB
mongoose.connect(config.DB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log("Db connected");

}).catch(err => console.log(err));



app.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
var jsonParser = bodyParser.json()
server.use('/api/v1/portfolio', portfolioRoutes);

server.get('/api/v1/secret', authService.checkJWT, (req,res) => {
    return res.json(secretData);

})

server.get('/api/v1/ownersite', authService.checkJWT, authService.checkRole('siteOwner'),
    (req,res) => {
    return res.json(secretData);

})

server.get('*', jsonParser,(req,res) => {
    return handle(req,res);
})

server.use(function (err, req, res, next){
    if (err.name === 'UnauthorizedError') {
        res.status(401).send({title: `Invalid token...`});
    }
});

server.use(handle).listen(3000, (err) => {
    if(err) throw err
    console.log('> Ready on http://localhost:3000');
})

}).catch((ex) => {
console.error(ex.stack)
process.exit(1);
})

这是我的路线:

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

const portfolioCtrl = require('../controllers/portfolio');
const authService = require('../services/auth');

router.route('').get(authService.checkJWT, authService.checkRole('siteOwner'),       
portfolioCtrl.getPortfolio);
router.route('').post(authService.checkJWT, authService.checkRole('siteOwner'),     
portfolioCtrl.savePortfolio);
router.route('/:id').patch(authService.checkJWT, authService.checkRole('siteOwner'),     
portfolioCtrl.updatePortfolio);
router.route('/:id').delete(authService.checkJWT, authService.checkRole('siteOwner'),     
portfolioCtrl.deletePortfolio);

module.exports = router;

这是我的控制器:

savePortfolio: (res, req) => {
    console.log(req);
    const portfolioData = req.body;
    const portfolio = new Portfolio(portfolioData);
    portfolio.save((err, createdPortfolio) => {
        if(err) {
            return res.status(422).send(err);
        }
        return res.json(createdPortfolio);
    })
},

标签: javascriptnode.jsmongodbexpressnext.js

解决方案


Express 路由的回调函数按以下顺序接受参数:

(req, res, next) =>{...}

  • req,请求对象。
  • res,响应对象。
  • next,表示下一个中间件功能(可选)

savePortfolio: (res, req) => {...}有错误的顺序。这就是req.body为什么undefined

更正:savePortfolio: (req, res) => {...}


推荐阅读