将中间件代码从 app.js 移动到它自己的函数和文件

Move middleware code from app.js to it's own function and file

在我的 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 is not defined"

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;

如何让它重新工作?

问题出在 /app/login 路由中,您正在使用 jwt 模块而没有在 app.js 中导入它 jwtSecret 也不在 [=25] 中=]现在。

我也看不出你是如何使用你在应用程序中创建的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
.
*/