为什么当我尝试使用Express和Body Parser进行发布时,我得到“name undefined”

我正在尝试构build一个MEAN应用程序,并尝试使用POSTMANtestingPOST。 当我这样做,我不断得到可怕的“TypeError:无法读取未定义的属性名称”。 如果我input一个简单的string,邮政通过罚款。 但是,当我使用“req.body.name”我得到的错误。 我看过每一个地方,我没有看到我的错误。 我甚至在没有运气的情况下遵循这个线程的build议。 任何帮助或build议将不胜感激。

这是我目前在我的server.js文件中使用的代码:

const express = require('express'); var bodyParser = require('body-parser'); var Bear = require('./models/bear') var path = require('path'); var mongoose = require('mongoose'); var router = express.Router(); var app = express(); var staticAssets = __dirname + '/public'; app.use(express.static(staticAssets)); app.use('/api', router) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // Routes for my API //=================================== // middleware to use for all requests router.use(function(req,res,next){ // logging happens here console.log('Something will happen.'); next(); // Head to the next router...don't stop here }); // Test router to make sure everything is working (accessed at GET http://localhost:3000/api) router.get('/', function(req, res){ res.json({message: 'hooray! welcome to our api!'}) }) //More routes will happen here with routes that end in "/bears" router.route('/bears') //Create a bear (accessed at POST http://localhost:3000/api/bears) .post(function(req,res){ var bear = new Bear(); // Create a new instance of the bear model console.log(req); bear.name = req.body.name; // set the bears name (comes from the request) //res.send(200, req.body); bear.save(function(err){ if (err) res.send(err); res.json({message: 'Bear Created!!'}); }); }); //====================================== //var Products = require('./products.model.js'); var Product = require('./models/product.model'); var db = 'mongodb://localhost/27017'; mongoose.connect(db); var server = app.listen(3000); console.log("App is listening on port 3000"); 

谢谢。

此外,我试图在POSTMAN里面使用的url是http:// localhost:3000 / api / bears

Expressstream程请求自顶向下(Top-Down),这意味着如果您需要通过中间件将所有路由应用于某个function,则需要在需要的任何路由之前将中间件添加到您的应用中。 中间件通常就是这种情况,比如body-parser

使用路由器中间件时,通常不会将路由器构build为与将用作中间件的实际快速应用程序相同的文件。 相反,将其放置在单独的文件和/或目录中用于组织目的,这被认为是最佳实践。

Express应用程序可以像这样构造

 /lib /models bear.js product.js /node_modules /public /css /routes api.js package.json server.js 

routes目录是你放置任何适用的路由器中间件文件的地方,比如你的api路由器。 server.js是您的主要快速应用程序, public是您的静态资产存储的地方。 lib是包含任何业务逻辑文件和模型的目录。

实际的Express应用程序和路由器文件应该是这样的

server.js

 'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const apiRouter = require('./routes/api'); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, public))); app.use(/api, apiRouter); app.listen(port, () => { console.log(`Listening on port ${port}); }); module.exports = app; 

路线/ api.js

 'use strict'; const router = require('express').Router(); const Bear = require('./lib/models/bear'); router.use((req, res, next) => { // logging happens here console.log('Something will happen.'); next(); // Head to the next router...don't stop here }); router.get('/', (req, res) => { return res.json({ message: 'hooray! welcome to our api!'}) }); router.route('/bears') //Create a bear (accessed at POST http://localhost:3000/api/bears) .post((req, res) => { var bear = new Bear(); // Create a new instance of the bear model console.log(req); bear.name = req.body.name; // set the bears name (comes from the request) //res.send(200, req.body); bear.save((err) => { if (err) return res.send(err); return res.json({message: 'Bear Created!!'}); }); }); module.exports = router; 

要注意的是,你可以进一步分解你的API来增加解耦的数量。 一个例子就是把/api/bear路由移到自己的路由器中间件,然后到自己的路由文件中去。 然后简单地将它添加到您的routes/api.js路由器中,就像在server.js 。 如果你的应用程序将有一个体面的大小的API,那么这将是最好的方法,因为它将允许最大的灵活性,当涉及到应用中间件只有某些路线,并将使维护源更容易。