【问题标题】:TypeError: Cannot read property 'email' of nullTypeError:无法读取 null 的属性“电子邮件”
【发布时间】:2021-09-06 06:18:22
【问题描述】:

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

【问题讨论】:

  • 你能告诉我们你是如何使用主文件中导出的路由器的吗?
  • 我已经编辑过了。你可以检查一下。
  • Express 本身没有解析表单数据格式的中间件。您可以将请求更改为 JSON 格式,如 Fabio 的建议。您还需要使用express.json() middleware。另外,post 路由之前有没有中间件?

标签: node.js api express postman


【解决方案1】:

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

{ “电子邮件”:“某事@某事”, “密码”:“某事” }

【讨论】:

  • 问题还是一样 :(
  • 你能发布 req.body 的输出吗?
【解决方案2】:

你还有更多问题:

  • 要解析请求正文,您需要安装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
        });
    }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多