问题描述
我正在尝试使用 express-jwt 创建登录功能,并在我的 app.js
文件中使用中间件功能。但是每当我尝试使用 postman
发送 get 请求时,它都会发送无限时间的请求并且永远不会返回任何错误或成功消息。
我使用 dynamoDB
作为数据库。
这是我的 Login.js
文件
const AWS = require("aws-sdk");
const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
require("dotenv").config();
AWS.config.update({ region: "us-east-2" });
const docclient = new AWS.DynamoDB.DocumentClient();
const router = express.Router();
router.post("/login",(req,res) => {
user_type = "customer";
const email = req.body.email;
docclient.get(
{
TableName: "users",Key: {
user_type,email,},(err,data) => {
if (err) {
res.send("Invalid username or password");
} else {
if (data && bcrypt.compareSync(req.body.password,data.Item.password)) {
const token = jwt.sign(
{
email: data.Item.email,process.env.SECRET,{ expiresIn: "1d" }
);
res.status(200).send({ user: data.Item.email,token: token });
} else {
res.status(400).send("Password is wrong");
}
}
}
);
});
module.exports = router;
这是我的 jwt.js
文件:
const expressJwt = require("express-jwt");
require("dotenv").config();
function authJwt() {
const secret = process.env.SECRET;
return expressJwt({
secret,algorithms: ["HS256"],});
}
module.exports = authJwt;
我正在尝试在我的 expressJwt
文件中使用这样的 app.js
:
app.use(authJwt); //If I'm not using this,then the code works fine without API protection
谁能告诉我我的代码有什么问题? 感谢您提供任何帮助。
解决方法
从你的 jwt.js 中删除函数,它应该是这样的
const expressJwt = require('express-jwt');
const secret = process.env.secret
const authJwt = expressJwt({
secret,algorithms:['HS256']
})
module.exports = authJwt;