[英]TypeScript add custom Request header in Express
我正在嘗試向我的請求添加一個自定義 header ,但它必須在界面中修改/實現。
默認Request
接口引用IncomingHttpHeaders
。 所以我試圖用我自己的自定義令牌 header 擴展這個接口。
import { IncomingHttpHeaders } from 'http';
declare module 'express-serve-static-core' {
interface IncomingHttpHeaders {
"XYZ-Token"?: string
}
}
我已經更新了我的.tsconfig
文件以讀取./types
文件夾。 我的文件名是index.d.ts
如果我不使用自定義 header,我可以成功編譯代碼,但是當我嘗試在代碼中引用令牌 header 時,出現以下編譯錯誤:
錯誤
error TS2538: Type 'string[]' cannot be used as an index type.
req.headers['XYZ-Token']
如果我使用原始接口的任何值,一切正常。
例子:
req.headers['user-agent']
附加信息:我正在使用 NestJS,它在底層使用 Fastify/Express。 我可以確認正在使用的 Request 接口來自 Express。 Fastify 向后兼容所有 Express 模塊。 主要使用 Fastify,因為它更快。
聲明中似乎有錯誤的模塊名稱。
盡管IncomingHttpHeaders
接口被附加到來自express-serve-static-core
的Request
object ,但IncomingHttpHeaders
接口的原始來源實際上是http
ZEFE90A8E604A7C640E88D03A67 的一部分
以下允許在代碼中訪問自定義 header 並正確編譯 ts。
import { IncomingHttpHeaders } from 'http';
declare module 'http' {
interface IncomingHttpHeaders {
"XYZ-Token"?: string
}
}
無論出於何種原因,它認為您傳入的字符串是一個數組,但除此之外,如果您需要設置自定義 header (並且它不是動態值),您可以使用@Header()
裝飾器。 如果它是動態的,那么您可以使用攔截器來獲取響應飛行前的響應,並將 header 設置為類似
@Injectable()
export class CustomHeaderInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next
.handle()
.pipe(
tap(() => context.switchToHttp().getResponse().header('XYZ-Token', customValue),
);
}
}
我最近遇到了這樣的問題,對我有用的解決方案是創建一個從IncomingHttpHeaders擴展的類型
import { IncomingHttpHeaders } from "http2";
interface MyCustomsHearders {
foo: "bar";
}
type IncomingCustomHeaders = IncomingHttpHeaders & MyCustomsHearders;
const { foo } = req.headers as IncomingCustomHeaders;
我知道這不是解決問題的最“正式”方法,但對我來說效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.