簡體   English   中英

使用 express 和 typescript 在 request.user 中獲取用戶數據

[英]Get user data in request.user using express and typescript

我正在嘗試創建一個中間件以確保用戶是管理員,但是當我打印request.customer時,結果是undefined

這就是我正在做的事情:

import { NextFunction, Request, Response } from "express";

import { prisma } from "../../prisma";

export async function ensureAdmin(
  request: Request,
  response: Response,
  next: NextFunction
) {
  const { id } = request.customer;
  const customer = await prisma.customer.findUnique({
    where: {
      id,
    },
  });

  console.log(request.customer);

  return next();
}

request.customer返回: Property 'customer' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'所以我通過添加客戶 ID 來聲明 express 命名空間,如下所示:

declare namespace Express {
  export interface Request {
    customer: {
      id: string;
    }
  }
}

我沒有錯誤,但同時當我打印request.customer時它是未定義的。

我認為您需要正確實現本文檔中描述的中間件:使用中間件

在那里你會得到(req, res, next) function。 req 是 Request 類型,包含查詢參數的參數(通過req.params )、標頭(通過req.headers['...']調用)等等。 無論您的客戶 ID 編碼在哪里,您都需要從您的請求中提取它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM