Node.js 为什么我会得到;“名称未定义”;尝试使用Express和主体解析器进行post时

Node.js 为什么我会得到;“名称未定义”;尝试使用Express和主体解析器进行post时,node.js,express,postman,Node.js,Express,Postman,我试图建立一个平均应用程序,并试图测试与邮递员张贴。当我这样做的时候,我总是会遇到可怕的“TypeError:无法读取未定义的属性'name'。如果我输入一个简单的字符串,帖子就会顺利通过。但是当我使用“req.body.name”时,我得到了错误。我找遍了每一个地方,没有发现我的错误。我甚至连这个建议都没有采纳。如有任何帮助或建议,将不胜感激 以下是我当前在server.js文件中使用的代码: const express = require('express'); var bodyPa

我试图建立一个平均应用程序,并试图测试与邮递员张贴。当我这样做的时候,我总是会遇到可怕的“TypeError:无法读取未定义的属性'name'。如果我输入一个简单的字符串,帖子就会顺利通过。但是当我使用“req.body.name”时,我得到了错误。我找遍了每一个地方,没有发现我的错误。我甚至连这个建议都没有采纳。如有任何帮助或建议,将不胜感激

以下是我当前在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是自上而下的Express processes requests,这意味着如果您需要通过中间件将一项功能应用于所有路由,则需要在需要它的任何路由之前将该中间件添加到您的应用程序中。这通常是中间件的情况,例如

使用路由器中间件时,您通常不会将路由器构建在将其用作中间件的实际Express应用程序的同一文件中。相反,出于组织目的,将其放在单独的文件和/或目录中,这被认为是最佳做法

Express应用程序可以这样构造

/lib
  /models
    bear.js
    product.js
/node_modules
/public
  /css    
/routes
  api.js
package.json
server.js
routes
目录是放置任何适用的路由器中间件文件(如
api
路由器)的地方
server.js
是您的主要Express应用程序,
public
是存储静态资产的地方
lib
是包含任何业务逻辑文件和模型的目录

实际的Express应用程序和路由器文件应该如下所示

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

你应该在问题中包括你的客户端请求。另一件事是,您应该将
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
移动到所有路由和路由器中间件之前。如果它没有出现在他们面前,那么在处理这些路线时它将不会被使用。因此,如果您正在请求您的
/api
路由器中间件,则不会使用
bodyParser
'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; 
'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;