gpt4 book ai didi

javascript - 将属性添加到 Express 请求对象

转载 作者:行者123 更新时间:2023-12-01 21:51:31 24 4
gpt4 key购买 nike

我正在尝试向 Express 请求对象添加属性“forwardingUrl”。

我尝试通过创建文件 ./typing.d.ts 来合并声明:

declare namespace Express {
export interface Request {
forwardingUrl: string;
}
}

在编辑器中我可以使用该属性并访问它但是当我编译时出现以下错误:

Property 'forwardingUrl' does not exist on type 'Request<ParamsDictionary>'.

我错过了什么?

编辑

出现错误的代码:

import { Middleware, Request } from '@tsed/common';
import { Request as ExpressRequest } from 'express';
@Middleware()
export class Wso2ForwardingUrlParser {
async use(@Request() request: ExpressRequest) {
if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {
request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;
} else {
request.forwardingUrl = '';
}
}
}

最佳答案

添加扩展请求的新模型

import {Request} from "@tsed/common";

export interface RequestModel extends Request {
forwardingUrl: string
}

然后在方法中使用它

import { Middleware, Request } from '@tsed/common';
import { Request as ExpressRequest } from 'express';
@Middleware()
export class Wso2ForwardingUrlParser {
async use(@Request() request: RequestModel) {
if (request.header('X_FORWARDED_HOST') && request.header('X_FORWARDED_PREFIX')) {
request.forwardingUrl = `https://${request.header('X_FORWARDED_HOST')}${request.header('X_FORWARDED_PREFIX')}`;
} else {
request.forwardingUrl = '';
}
}
}

关于javascript - 将属性添加到 Express 请求对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59343683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com