【发布时间】:2016-11-09 04:55:08
【问题描述】:
我正在尝试构建一个 MEAN 应用程序并尝试使用 POSTMAN 测试 POST。当我这样做时,我不断收到可怕的“TypeError:无法读取未定义的属性'名称'”。如果我输入一个简单的字符串,则 POST 可以正常运行。但是当我使用“req.body.name”时,我得到了错误。我已经查看了每个地方,但我没有看到我的错误。我什至没有运气就遵循了thread 的建议。任何帮助或建议将不胜感激。
这是我目前在 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 中尝试使用的网址是 http://localhost:3000/api/bears
【问题讨论】:
-
您应该在问题中包含您的客户请求。另一件事是您应该在所有路由和路由器中间件之前移动您的
app.use(bodyParser.json())和app.use(bodyParser.urlencoded({extended: true}))。如果它没有出现在它们之前,那么在处理这些路由时将不会使用它。因此,如果您请求/api路由器中间件,则不会使用bodyParser。