node.js - node.js express 中的“return next()”抛出“下一个未定义”错误
问题描述
我正在开发一个 node.js 应用程序。
在我的应用程序中,请求通过一个中间件检查用户是否经过身份验证。不过,在我的中间件文件中,我的客户端中不断出现“下一个未定义”错误。可能是什么问题?我在这里添加 App.js 和中间件文件:
应用程序.js:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const { sequelize } = require('./models');
const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');
const auth = require('./middleware/auth');
// return instance of the app
app = express();
// setting up the cors config
app.use(cors({
origin: '*'
}));
// tell the app to parse the body of the request
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// tell the app to go through the middleware before proceeding to graphql
app.use(auth);
// setting the graphql route
app.use('/graphql', graphqlHttp({
schema: graphqlSchema,
rootValue: graphqlResolver,
graphiql: true,
formatError(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const message = err.message || 'An error occurred.';
const code = err.originalError.code || 500;
return { message: message, status: code, data: data };
}
})
);
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
const data = error.data;
res.status(status).json({ message: message, data: data });
});
sequelize.sync({ force: true })
.then(() => {
app.listen(8080);
})
.catch(err => {
console.log(err);
});
auth.js 文件(中间件):
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
const authHeader = req.get('Authorization');
if (!authHeader) {
req.isAuth = false;
return next();
}
const token = authHeader.split(' ')[1];
let decodedToken;
try {
decodedToken = jwt.verify(token, 'somesupersecretsecret');
} catch (err) {
req.isAuth = false;
return next();
}
if (!decodedToken) {
req.isAuth = false;
return next();
}
req.userId = decodedToken.userId;
req.isAuth = true;
next();
};
解决方案
推荐阅读
- javascript - JS 获取类的类名
- c - 为什么即使代码正确,该程序也会显示其他内容?
- python - 如何获取具有已知名称的列左侧的列名?
- excel - 如何创建一个函数来计算 Excel 中过滤行的平均值
- sql - 如何通过有子句在 SQL 中聚合
- google-apps-script - 无法设置复选框 DataValidation
- php - PHP Symfony Swift_Mailer 错误:# 无法从后端获取响应:格式错误的 MIME 标头:缺少冒号:%!!(MISSING)q(MISSING)#5 {main}
- python - Youtube_DL 没有属性'from_url'
- matplotlib - 这是什么剧情?
- c - 在编译时设置指针类型