将中间件代码从app.js移至其自己的函数和文件中

问题描述 投票:-2回答:1

在我的app.js文件中,我有一些用于身份验证的中间件,如下所示:

const jwt = require("jsonwebtoken");
const jwtSecret = "mysuperdupersecret"; // actually in .env file

app.use((req, res, next) => {
  if (req.path == "/api/login") {
    return next();
  }

  const token = req.headers.authorization;


  try {
    var decoded = jwt.verify(token, jwtSecret);
    console.log("decoded", decoded);
  } catch (err) {
    // Catch the JWT Expired or Invalid errors
    return res.status(401).json({ msg: err.message });
  }

  next();
});

我创建了一个中间件文件夹,并在其中放置了一个名为'auth.js'的文件。然后将这段代码放在其中:

const jwt = require("jsonwebtoken");
const jwtSecret = "mysuperdupersecret";

function auth(req, res, next) {
  if (req.path == "/api/login") {
    return next();
  }

  const token = req.headers.authorization;


  try {
    var decoded = jwt.verify(token, jwtSecret);
    console.log("decoded", decoded);
    next();
  } catch (err) {
    return res.status(401).json({ msg: err.message });
  }
}

module.exports = auth;

在执行此操作之前,我的应用程序正在运行。现在,我收到500个内部服务器错误;消息“:”未定义jwt“

app.js

const express = require("express");
const app = express();

// CORS middleware
app.use(function(req, res, next) {
  // Allow Origins
  res.header("Access-Control-Allow-Origin", "*");
  // Allow Methods
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  // Allow Headers
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, Accept, Content-Type, Authorization"
  );
  // Handle preflight, it must return 200
  if (req.method === "OPTIONS") {
    // Stop the middleware chain
    return res.status(200).end();
  }
  // Next middleware
  next();
});

// Routes
app.get("/api/login", (req, res) => {
  const token = jwt.sign({ username: "test" }, jwtSecret, { expiresIn: 60 }); // 1 min token
  res.json({ token: token });
});

app.get("/api/token/ping", (req, res) => {
  res.json({ msg: "all good mate" });
});

app.get("/api/ping", (req, res) => {
  res.json({ msg: "pong" });
});

module.exports = app;

我如何使其重新工作?

reactjs jwt middleware next.js
1个回答
1
投票

问题出在/app/login路由中,您正在使用jwt模块而不将其导入到app.js中,而且jwtSecret现在也不在app.js内。

我也看不到您如何使用在应用程序中创建的auth.js

您可以将auth.js更新为

const jwt = require("jsonwebtoken");
const jwtSecret = "mysuperdupersecret";

function auth(req, res, next) {
  if (req.path == "/api/login") { // check for HTTP GET/POST if required
    const token = jwt.sign({ username: "test" }, jwtSecret, { expiresIn: 60 }); // 1 min token
    res.json({ token: token });
  }
  else {
    const token = req.headers.authorization;
    try {
      var decoded = jwt.verify(token, jwtSecret);
      console.log("decoded", decoded);
      next();
    } catch (err) {
      return res.status(401).json({ msg: err.message });
    }
  }
}

在app.js中]

/*.
.
. other code
*/
const auth = require('./auth.js');

app.use(auth);

/*.
. remaining code
.
*/
© www.soinside.com 2019 - 2024. All rights reserved.