正文解析器导致未定义

时间:2019-04-04 14:43:36

标签: javascript express post body-parser

尝试做一个简单的POST请求主体的console.log。我在Chrome控制台中看到有效数据,其中包含正确的数据,但是当我尝试读取数据时,出现以下错误:

express_1  | TypeError: Cannot read property 'exampleval' of undefined

我过去曾经使用过这种确切的逻辑,但从未遇到过问题。

services / router.js

const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
var app = express();
    // parse application/json
    app.use(bodyParser.json());                        

    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }));
const router = new express.Router();
const employees = require('../controllers/employees.js');


//router.route('/employees').post(employees.post);

router.post('/employees', function (req, res) {
    var exampleval = req.body.exampleval;
    console.log(exampleval);
})

module.exports = router;

services / web-server.js

const http = require('http');
const express = require('express');
const webServerConfig = require('../config/web-server.js');
const bodyParser = require('body-parser');
const router = require('./router.js');
const morgan = require('morgan');
const cors = require('cors');


let httpServer;

function initialize() {
  return new Promise((resolve, reject) => {
    const app = express();
    httpServer = http.createServer(app);
    // Combines logging info from request and response
    app.use(morgan('combined'));
    // enable cors on all routes
    app.use(cors())
    // Mount the router at /api so all its routes start with /api
    app.use('/api', router);
    // Body Parser
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));

    httpServer.listen(webServerConfig.port)
      .on('listening', () => {
        console.log(`Web server listening on localhost:${webServerConfig.port}`);

        resolve();
      })
      .on('error', err => {
        reject(err);
      });
  });
}

module.exports.initialize = initialize;

function close() {
    return new Promise((resolve, reject) => {
      httpServer.close((err) => {
        if (err) {
          reject(err);
          return;
        }

        resolve();
      });
    });
  }

module.exports.close = close;

我相信这些是代码中仅有的两个相关部分。任何建议都将不胜感激,因为我感觉我非常亲密。我的希望是最终将这些值传递给SQL查询。

1 个答案:

答案 0 :(得分:0)

中间件顺序很重要。

// Mount the router at /api so all its routes start with /api
app.use('/api', router);
// Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

应该是

// Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// Mount the router at /api so all its routes start with /api
app.use('/api', router);

,以便路由器仅在正文解析器附加了req.body后才接收请求(可能要处理)。