这是每次我尝试使用 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;
答案 0 :(得分:0)
您有更多问题:
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", “密码”:“东西” }