在我的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;
我如何使其重新工作?
问题出在/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
.
*/