向 Express 请求对象添加属性
Posted
技术标签:
【中文标题】向 Express 请求对象添加属性【英文标题】:Add Property to Express Request Object 【发布时间】:2020-04-08 03:39:51 【问题描述】:我正在尝试“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 = '';
【问题讨论】:
请求已经存在 developer.mozilla.org/en-US/docs/Web/API/Request 这是 Requestexport interface Request
没有任何“扩展”。您能否包含出现错误的代码,同时显示导入。
【参考方案1】:
我遇到了同样的问题,并通过在抛出错误的行上方添加//@ts-ignore
来解决它:
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'))
//@ts-ignore
request.forwardingUrl = `https://$request.header('X_FORWARDED_HOST')$request.header('X_FORWARDED_PREFIX')`;
else
//@ts-ignore
request.forwardingUrl = '';
我还建议稍后在代码中使用参数装饰器来获取此值。由于您已经通过中间件将这个额外的“forwardingUrl”属性添加到请求实例中,因此创建一个参数装饰器,如下所示:
// ./ForwardingUrlDecorator.ts
import createParamDecorator from '@nestjs/common';
export const ForwardingUrl = createParamDecorator((_data: any, req: any) =>
return req.forwardingUrl;
);
然后在您的控制器中,您可以获取该值,而无需在您的方法中将整个 express 实例作为参数引用:
import Controller from '@nestjs/common';
import ForwardingUrl from './ForwardingUrlDecorator';
@Controller()
export class YourController
@Get()
public async getTheThing(@ForwardingUrl() forwardingUrl: string)
//...
【讨论】:
【参考方案2】:添加扩展 Request 的新模型
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 = '';
【讨论】:
【参考方案3】:在nestjs中为Express Request Object添加自定义属性,
创建一个名为 express 的新文件夹并添加新文件 index.d.ts,使用以下内容,
export ;
export type _Foo = Foo;
declare global
namespace Express
interface Request
foo: _Foo;
【讨论】:
以上是关于向 Express 请求对象添加属性的主要内容,如果未能解决你的问题,请参考以下文章