类型错误:无法读取 null 的属性“电子邮件”

时间:2021-06-22 16:13:57

标签: node.js api express postman

这是每次我尝试使用 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;

enter image description here

app.js(主文件)

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

module.exports = app;

2 个答案:

答案 0 :(得分:0)

您有更多问题:

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

这是一个如何实现快速 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
        });
    }

});

答案 1 :(得分:-1)

您正在使用表单数据。尝试在 body => raw => json 中使用:

{ "email": "something@something", “密码”:“东西” }