typescript 如何检查我是否在我的代码中得到了我的'jwt'令牌?

z31licg0  于 2023-10-22  发布在  TypeScript
关注(0)|答案(1)|浏览(134)

我试图让我的数据,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,
    });
  }
}

现在请告诉我这里有什么问题??

zu0ti5jz

zu0ti5jz1#

显示错误error: jwt must be provided,因为您从cookie获取的令牌为空!从token捕获您从cookie获取的日志。
重要的是,在Next.js中获取Server SideClient中的cookie是不同的!

相关问题