Aay*_*ngh 2 typescript next.js
我是 next.js 和 typescript 的新手,我对这个问题感到非常沮丧,因为已经 4 天了,我找不到解决方案。如果有人知道原因和问题,请帮助我解决方案。这会很有帮助的。谢谢
-- 这是我的中间件.ts
import jwt from "jsonwebtoken";
import { NextResponse, NextRequest } from "next/server";
import clientPromise from "./database/db";
interface RequestWithUserId extends NextRequest {
userId: string;
}
export async function middleware(req: RequestWithUserId) {
try {
const mongoClient = await clientPromise;
const token = req.cookies.get("jwt")?.value;
if (!token) {
return NextResponse.redirect("http://localhost:3000/login");
}
const decodedToken: any = jwt.verify(token, process.env.SECRET_KEY);
const userId = decodedToken._id;
const checkUserExists = await mongoClient
.db()
.collection("user")
.findOne({ _id: userId });
if (!checkUserExists) {
return NextResponse.redirect("http://localhost:3000/login");
}
req.userId = userId;
return NextResponse.next();
} catch (err) {
console.log("miidleware error", err);
NextResponse.redirect("http://localhost:3000/login");
}
}
export const config = {
matcher: "/api/addToCart",
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9251 次 |
| 最近记录: |