我似乎无法解决这个问题。我在 http://localhost:5000/sysaccess/test 点击此 URL 时收到此错误消息。
(节点:34256( 未处理的承诺拒绝警告:未处理的承诺拒绝(拒绝 ID:1(:强制转换错误:模型"系统访问"的路径"_id"处的值"test"强制转换为 ObjectId 失败(节点:34256([DEP0018]弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止 Node.js 进程。
在我的系统访问中.js路由我有这个:
const express = require('express');
const csv = require('csv-express');
const mongoose = require('mongoose');
const router = express.Router();
const {ensureAuthenticated} = require('../helpers/auth');
const Sysaccess = mongoose.model('sysaccess');
const Vendor = mongoose.model('vendor');
router.get('/test', (req, res) => {
res.send('ok');
});
我已经将系统访问.js路由与我的供应商进行了比较.js路由,一切似乎都很好。我在供应商中有十几条路线.js没有任何问题。我花了很多时间谷歌这个,但没有找到任何东西。有人可以告诉我我在这里错过了什么。提前谢谢你!
sysaccess.js
路由器中中间件的顺序错误。
例如:
// "GET /sysaccess/test" will be processed by this middleware
router.get('/:id', (req, res) => {
let id = req.params.id; // id = "test"
Foo.findById(id).exec().then(() => {}); // This line will throw an error because "test" is not a valid "ObjectId"
});
router.get('/test', (req, res) => {
// ...
});
解决方案 1:让那些更具体的中间件先于那些更通用的中间件。
例如:
router.get('/test', (req, res) => {
// ...
});
router.get('/:id', (req, res) => {
// ...
});
解决方案 2:使用 next
将请求传递给下一个中间件
例如:
router.get('/:id', (req, res, next) => {
let id = req.params.id;
if (id === 'test') { // This is "GET /sysaccess/test"
return next(); // Pass this request to the next matched middleware
}
// ...
});
router.get('/test', (req, res) => {
// ...
});