node.js - 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;
解决方案
你还有更多问题:
- 要解析请求正文,您需要安装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
});
}
});
推荐阅读
- python - 如何创建 3d 散点图
- java - 如何安全地从另一个线程处理模态对话框?
- amazon-web-services - AWS::ApiGateway::Method 在每次部署中都被删除
- apple-push-notifications - WatchKit Complication 推送应用标识符/证书(WWDC20)
- node.js - node-postgres:在 client.end() 之后 Postgres 客户端仍然连接?
- google-cloud-platform - GCP AI Notebook 无法访问存储桶
- python - OS 库或其他 python 库中是否有一个函数可以检查文件扩展名是什么
- angular - IIS:找不到页面时重定向到索引
- hyperledger-fabric - 调试 TLS 握手失败
- java - 无法在rest api中传递字符串数组