繁体   English   中英

NODE.JS(TYPESCRIPT) 类型“NodeModule”上不存在属性“req”

[英]NODE.JS(TYPESCRIPT) Property 'req' does not exist on type 'NodeModule'

我在子文件中使用 this.status 和 this.req 时遇到问题

我像这样初始化路由索引

router.use(response);

我的索引文件在下面

import {Request,Response,NextFunction} from 'express'

module.exports = function(req:Request, res:Response, next:NextFunction){
    const responseTypes = {
        unprocessable: require('./unprocessable')
    };

    res = {...res, ...responseTypes};
    next();
};

这是我的 unprocessable.ts 文件

import log from '../logger'
import queue from '../queue'

module.exports = function (data, message) {
    log.warn('Sending unprocessable entity response: ', data, message || 'unprocessable entity');
    const req = this.req;
    const res = this;

    // Dump it in the queue
    const response = { response: { status: 'error', data: data, message: message ? message : 'unprocessable entity' } };
    response.requestId = req.requestId;

    queue.add('logResponse', response);

    if (data !== undefined && data !== null) {
        if (Object.keys(data).length === 0 && JSON.stringify(data) === JSON.stringify({})) {
            data = data.toString();
        }
    }

    if (data) {
        this.status(422).json({ status: 'error', data: data, message: message ? message : 'unprocessable entity' });
    } else {
        this.status(422).json({ status: 'error', message: message ? message : 'unprocessable entity' });
    }
};

它在 unprocessable.ts 文件中抱怨以下内容

如果我使用 this.status,则类型“NodeModule”上不存在属性“状态”

如果我使用 this.req,则类型“NodeModule”上不存在属性“req”

我不知道如何解决它,因为我是 typescript 的新手

Typescript 在大多数情况下不知道您在使用this关键字时指的是什么。

但是,您可以告诉 typescript 您的意思是this ,例如:

function someFunction(this: object) {
  // do something with this
}

在您的情况下, this是指从 express 扩展Response的 object ,因此您可以做的是:

const { Response } = require('express');

interface IModifiedResponse extends Response {
  // define your properties here
  unprocessable: (data: object, message: string) => void
}

function unprocessable(this: IModifiedResponse, data: object, message: string) {
  // use this as in your function
}

但是我不知道 this.req 指的是什么,因为 Response 没有 req 属性。 请参阅ExpressJS 文档

希望这个答案有帮助:)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM