我试图让我的数据,jwt
实际上持有的引擎盖下,我这样做使用next.js
,但问题是我得到错误error: jwt must be provided
我努力尝试,但找不到任何东西,为什么这hapening:下面是我代码:getMyData.ts这是一个使用jwt token获取的函数:
import { NextRequest } from "next/server";
import jwt from 'jsonwebtoken';
export const GetDataFromToken = (request:NextRequest)=>{
try {
const token = request.cookies.get('secret')?.value||''
const decodeToken: any = jwt.verify(token,'secretvslueforauth')
return decodeToken.id
} catch (error: any) {
throw new Error(error.message)
}
}
这是我发送请求me.ts
的实际路由
import { connect } from "@/dbConfig/dbConfig";
import { NextRequest, NextResponse } from "next/server";
import { GetDataFromToken } from "@/helpers/getDataFromToken";
import User from "@/models/userModel";
// Establish the database connection
connect();
export async function GET(request: NextRequest) {
try {
// Get the user ID from the JWT token
const userId = await GetDataFromToken(request);
// Fetch the user data from the database based on the user ID
const user = await User.findOne({ id: userId }).select("-password");
console.log(user,"data")
if (!user) {
// If the user is not found, you can return an appropriate response
return NextResponse.json({
message: "User not found",
});
}
// If user data is found, return it as a JSON response
return NextResponse.json({
message: "Success",
data: user,
});
} catch (error: any) {
// Handle errors and return an appropriate error response
console.error("Error:", error);
return NextResponse.json({
error: error.message,
});
}
}
现在请告诉我这里有什么问题??
1条答案
按热度按时间zu0ti5jz1#
显示错误
error: jwt must be provided
,因为您从cookie获取的令牌为空!从token
捕获您从cookie获取的日志。重要的是,在
Next.js
中获取Server Side
和Client
中的cookie是不同的!