我在中间件函数中使用jsonwebtoken进行验证。但是在我的中间件函数中,我没有得到任何令牌,而是在我的数据库中生成了令牌。我不明白是什么问题。我试图控制台日志authmiddleware,但它显示没有提供令牌。
useModel.js:
const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const userSchema = new mongoose.Schema({
fname: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
unique: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("Not valid email address");
}
},
},
mobile: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
minlength: 6,
},
cpassword: {
type: String,
required: true,
minlength: 6,
},
tokens: [
{
token: {
type: String,
required: true,
},
},
],
carts: Array,
});
// password hasing
userSchema.pre("save", async function (next) {
if (this.isModified("password")) {
this.password = await bcrypt.hash(this.password, 12);
this.cpassword = await bcrypt.hash(this.cpassword, 12);
}
next();
});
// password hashing
userSchema.pre("save", async function (next) {
if (this.isModified("password")) {
const saltRounds = 12;
this.password = await bcrypt.hash(this.password, saltRounds);
this.cpassword = await bcrypt.hash(this.cpassword, saltRounds);
}
next();
});
// generating token
userSchema.methods.generateAuthToken = async function () {
try {
const token = jwt.sign({ _id: this._id }, process.env.JWT_SECRET, {
expiresIn: "1d",
});
this.tokens = this.tokens.concat({ token });
await this.save();
return token;
} catch (error) {
console.log(error);
}
};
// add to cart data
userSchema.methods.addToCart = async function (cart) {
try {
this.carts.push(cart);
await this.save();
return this.carts;
} catch (error) {
console.log("Error occurred while adding to cart: ", error);
}
};
const User = new mongoose.model("USER", userSchema);
module.exports = User;
Authmiddleware.js:
const jwt = require("jsonwebtoken");
const User = require("../models/userSchema");
const authmiddleware = async (req, res, next) => {
try {
const token = req.cookies.Amazon_website;
const verifyToken = jwt.verify(token, process.env.JWT_SECRET);
const rootUser = await User.findOne({
_id: verifyToken._id,
"tokens.token": token,
});
if (!rootUser) {
throw new Error("User Not Found");
}
req.token = token;
req.rootUser = rootUser;
req.userID = rootUser._id;
next();
} catch (error) {
if (error.name === "TokenExpiredError") {
res.status(401).send("Unauthorized: Token has expired");
} else {
res.status(401).send("Unauthorized: No token provided");
}
console.log(error);
}
};
module.exports = authmiddleware;
Controller.js:
const Products = require("../models/productSchema");
const User = require("../models/userSchema");
const bcrypt = require("bcryptjs");
//Login Controller
const loginController = async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
res.status(400).json({
error: "Fill the data",
});
// console.log("No data available");
}
try {
const userlogin = await User.findOne({ email: email });
// console.log(userlogin);
if (userlogin) {
const isMatch = await bcrypt.compare(password, userlogin.password);
console.log(isMatch);
if (!isMatch) {
res.status(400).json({ error: "Invalid crediential pass" });
} else {
const token = await userlogin.generateAuthToken();
console.log(token);
res.cookie("Amazon_website", token, {
expires: new Date(Date.now() + 1800000),
httpOnly: true,
});
res.status(201).json(userlogin);
}
} else {
res.status(400).json({ error: "User doesn't exist" });
}
} catch (error) {
res.status(400).json({
error: "Invalid Details",
});
}
};
//logout controller
const logoutController = async (req, res) => {
try {
req.rootUser.tokens = req.rootUser.tokens.filter((currentelement) => {
return currentelement.token !== req.token;
});
res.clearCookie("Amazon_website", { path: "/" });
req.rootUser.save();
res.status(201).json(req.rootUser.tokens);
console.log("user logout");
} catch (error) {
console.log(error);
}
};
//Add cart item
const addtocartController = async (req, res) => {
try {
const { id } = req.params;
const cart = await Products.findOne({ id: id });
console.log(cart + "Data of cart");
const userContact = await User.findOne({ _id: req.userID });
console.log(userContact + " Get User");
if (userContact) {
const cartData = await userContact.addTOCartData(cart);
await userContact.save();
console.log(cartData);
res.status(201).json(userContact);
} else {
res.status(401).json({
error: "Invalid User",
});
}
} catch (error) {
res.status(400).json({
error: "Invalid User",
});
}
};
module.exports = {
loginController,
logoutController,
addtocartController
};
userRoutes.js:
const express = require("express");
const {
loginController,
logoutController
} = require("../controller/Controller");
const authmiddleware = require("../middleware/Authmiddleware");
//router abject
const router = new express.Router();
//POST || login
router.post("/login", loginController);
//GET || logout
router.get("/logout", authmiddleware, logoutController);
module.exports = router;
cartRoutes.js:
const express = require("express");
const {
addtocartController,
cartDetailsController,
deletecartItemController,
} = require("../controller/Controller");
const authmiddleware = require("../middleware/Authmiddleware");
//router abject
const router = new express.Router();
//POST || add data into cart
router.post("/addtocart/:id", authmiddleware, addtocartController);
//GET || Get cart items
router.get("/cartdetails", authmiddleware, cartDetailsController);
//DELETE || remove item from cart
router.delete("/remove/:id", authmiddleware, deletecartItemController);
module.exports = router;
server.js:
const express = require("express");
const colors = require("colors");
const morgan = require("morgan");
const dotenv = require("dotenv");
const cors = require("cors"); // Import the cors package
const connectDB = require("./config/db");
const Products = require("./models/productSchema");
const DefaultData = require("./defaultdata.");
const cookieParser = require("cookie-parser");
dotenv.config();
connectDB();
const app = express();
app.use(express.json());
app.use(cors({ origin: "http://localhost:3000", credentials: true }));
app.use(cookieParser());
app.use(morgan("dev"));
app.use("/api/v1/user", require("./routes/userRoutes"));
app.use("/api/v1/product", require("./routes/productRoutes"));
app.use("/api/v1/cart", require("./routes/cartRoutes"));
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(
`Server is running in ${process.env.NODE_MODE} Mode on port ${process.env.PORT}`
.bgCyan.white
);
});
DefaultData();
无论我在那个文件中使用authmiddleware函数,我都会得到这个jsonwebtoken错误。我不明白这是什么问题。工作很好。但在我上传后端到一个网站,并尝试运行应用程序,然后发生错误。在那之后,我再次尝试从localhost:8080运行,但现在它不再工作了。
1条答案
按热度按时间yqkkidmi1#
请打印const verifyToken = jwt.verify(token,process.env.JWT_SECRET)之前的token;
检查这个问题。
Having trouble with JsonWebToken; JsonWebToken Error: JWT must be provided