UnhandledPromiseRejectionWarning:TypeError无法读取未定义的属性“名称”

时间:2019-10-17 10:59:32

标签: node.js mongodb

我正在尝试使用node express和mongoose创建用户登录和注册... 创建了用户模型...。现在尝试在我的路由器auth.js中添加post方法 但由于某种原因,我不断收到错误 无法读取未定义的属性“名称” 昨天我编写了完全相同的代码,但是使用其他一些发布方法,它运行得很好。...

我只希望现在就可以在邮递员上工作,仅此而已...非常感谢

auth.js file

User.js File

enter image description here

2 个答案:

答案 0 :(得分:1)

原来,中间件的顺序在这里很重要...我只是在路由添加、、、和之前就将app.use(express.json())移到了,而且一切都很好。...感谢Subburaj。 ..感谢您的帮助:)

答案 1 :(得分:0)

我仍然会收到错误消息: “((node:8452)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性'name'”

请在下面写下代码。我看不到我在想什么。预先感谢您的帮助!

软件包:

{
  "name": "grant-app",
  "version": "1.0.0",
  "description": "Grant tracking app for flaw.uniba.sk",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mongoose": "^5.7.7"
  },
  "devDependencies": {
    "nodemon": "^1.19.4"
  }
}

服务器:

const express = require('express');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
dotenv.config();

const app = express();
//middlewear
app.use(express.json());

//connect to DB
mongoose.connect(
    process.env.DB_CONNECT,
    { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true },
    () => console.log('Connected to DB!')
);

//import routes
const authRoute = require('./routes/auth');
//route middleware
app.use('/api/user', authRoute)

app.listen(3000, () => console.log("Server is up and running"));

路线:

const router = require('express').Router();
const User = require('../models/User');

router.post('/register',  async (req, res) => {
    const user = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    });
    try {
        const savedUser = await user.save();
        res.send(savedUser);
    } catch(err) {
        res.status(400).send(err);
    }
});

module.exports = router;

型号:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        min: 6,
        max: 255
    },
    email: {
        type: String,
        required: true,
        min: 6,
        max: 255
    },
    password: {
        type: String,
        required: true,
        min: 6,
        max: 1024
    }, 
    }, 
    {
        timestamps: true,
    }
);

module.exports = mongoose.model('User', userSchema);