在Express里使用中间件报错求教 Nodejs
在Express里使用中间件报错求教 Nodejs
最近在基于Express开发一个RESTful的Blog,登录认证后检查req.headers里的authorization,验证其token。
打算利用中间件来进行每次验证。
完成中间件代码后,在app.js里添加代码app.use(auth);
然后在index.js里使用:
app.put('/articles/:id', auth, function(){
//do someting
})
然后就报错:ReferenceError: auth is not defined
各种无解后来求教。。。
当然可以。根据你描述的问题,“ReferenceError: auth is not defined”,这通常意味着你的 auth
中间件没有被正确地定义或导入。我们需要确保 auth
中间件被正确地创建并加载到 Express 应用程序中。
以下是一个完整的示例,展示如何定义和使用一个简单的中间件来处理认证:
定义中间件
首先,在你的项目中创建一个文件,例如 authMiddleware.js
,用于定义中间件逻辑。这里我们假设你需要验证 req.headers.authorization
字段中的 token。
// authMiddleware.js
const jwt = require('jsonwebtoken');
function auth(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.status(401).send('Access Denied');
try {
const verified = jwt.verify(token, 'yourSecretKey');
req.user = verified;
next();
} catch (err) {
res.status(400).send('Invalid Token');
}
}
module.exports = auth;
在应用中使用中间件
接下来,在你的 app.js
文件中导入并使用这个中间件:
// app.js
const express = require('express');
const app = express();
const auth = require('./authMiddleware'); // 导入中间件
app.use(express.json()); // 如果你使用JSON格式的数据
// 使用中间件
app.use(auth);
// 示例路由
app.put('/articles/:id', function(req, res) {
// 这里你可以访问已验证的用户信息,例如 req.user
res.send(`Updating article ${req.params.id}`);
});
// 启动服务器
app.listen(3000, () => console.log('Server running on port 3000'));
在特定路由中使用中间件
如果你只想在某些特定的路由上使用这个中间件,可以在这些路由定义中直接使用它,如你在问题中提到的方式:
// index.js
const express = require('express');
const app = express();
app.put('/articles/:id', auth, function(req, res) {
// do something
res.send(`Updating article ${req.params.id}`);
});
module.exports = app;
通过上述步骤,你应该能够解决 auth is not defined
的错误,并成功地在 Express 应用程序中使用中间件进行认证。
auth没有定义,可以用passport库做认证的中间件,也可以自己写。
第一,auth是否是已经require相应的中间件模块了 第二,已经用app.use()全局使用中间件了,为什么还要在特定路由中再使用该中间件
感谢回复。
原来app.use()是全局使用,难怪。
要实现部分路由使用需要在部分路由设置,是这个意思吧?:)
根据你的描述,错误 ReferenceError: auth is not defined
表明你在尝试调用 auth
中间件时,它并没有被正确地定义或导入。这通常是因为没有在正确的文件中定义 auth
或者在使用之前没有正确引入。
示例代码
假设你有一个文件结构如下:
- app.js
- index.js
- middlewares/
- auth.js
auth.js (定义中间件)
// middlewares/auth.js
module.exports = function(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(403).send({ message: 'No token provided.' });
}
// 这里可以添加你的token验证逻辑
// 假设验证通过
next();
};
app.js (注册中间件)
// app.js
const express = require('express');
const app = express();
const auth = require('./middlewares/auth');
// 注册全局中间件
app.use(auth);
// 其他路由定义
app.put('/articles/:id', function(req, res) {
// do something
res.send('Updating article with ID: ' + req.params.id);
});
module.exports = app;
index.js (启动应用)
// index.js
const app = require('./app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
解释
- 定义中间件:在
auth.js
文件中定义了auth
中间件,并导出它。 - 导入中间件:在
app.js
文件中导入并使用auth
中间件。 - 使用中间件:在需要使用
auth
验证的路由前添加该中间件。
确保路径和文件名一致,避免因拼写错误导致 auth
未定义的情况。这样配置后,你应该不会再遇到 ReferenceError: auth is not defined
的错误。