首页 > 解决方案 > 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();
};

标签: node.jsexpress

解决方案


推荐阅读