首页 > 解决方案 > TypeError:无法读取 null 的属性“电子邮件”

问题描述

这是每次我尝试使用 Postman 检查登录功能时都会出现上述错误的管理路线,我是 NodeJS 的新手,所以请帮忙。

const express = require('express');
const Admin = require('../models/admin');

const router = express.Router();

router.post('', (req, res, next) => {
    Admin.findOne({ email: req.body.email, password: req.body.password })
        .then(Admin => {
            if (req.body.email == Admin.email) {
                res.status(200).json({
                    message: 'Admin allowed!'
                 });
            }
            else{
                res.status(401).json({
                    message: 'Unauthorized!'
                })
            }
            
        })
        .catch(err => {
            console.log('error: ', err);
        })
    })

    
module.exports = router;

在此处输入图像描述

app.js(主文件)

 const adminRoutes = require('./routes/admin');
    app.use('/api/admin', adminRoutes);

module.exports = app;

标签: node.jsapiexpresspostman

解决方案


你还有更多问题:

  • 要解析请求正文,您需要安装body-parser
  • 声明了错误的路由路径router.post('', ...。从屏幕截图中我看到了路径router.post('/api/admin', ...
  • 您将结果的名称设置为模型名称.then(Admin => {。这是错的。您需要设置不同的变量名称.then((user) => {
  • 您尝试检查来自正文和模型的电子邮件是否相同,但是当您调用时,此检查 mongo 会执行此操作.findOne()

下面是一个如何实现 express api 路由的示例:

const express = require('express');
const bodyParser = require('body-parser');
const Admin = require('../models/admin');

const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

         // here you define path
app.post('/api/admin', async (req, res) => {

    try {
        
                      // mongo db query
        const admin = await Admin.findOne({ email: req.body.email, password: req.body.password });
        // check if have data
        if (!admin) {
            res.status(401).json({
                message: 'Unauthorized!'
            });
        }

        res.status(200).json({
            message: 'Admin allowed!'
        });

    } catch (e) {
        res.status(500).json({
            error: e
        });
    }

});


推荐阅读