首页 > 解决方案 > 如何在打字稿中添加扩展功能来表达响应?

问题描述

我想在 Express 中扩展 Response 以包含自定义函数。我想添加一个功能:

sendError(statusCode: number, errorMessage: string)

这样我就可以在任何地方调用它

response.sendError(500, "Unable to process this request at the moment.")

你能告诉我如何实现这一目标吗?我查看了其他一些问题,例如 typescript 中数字的扩展方法,但我仍然有一些疑问:

  1. 当没有原型时,如何在 Response 上扩展函数?
  2. 我把扩展函数的定义放在哪里?我可以制作一个包含所有定义的单独文件吗?
  3. 我是否必须将此函数分配给 Response 的每个对象才能使用它,或者我可以只定义一次并在我项目中任何地方的所有响应对象上使用它?

请帮我解决一下这个。我是 TypeScript 的新手,所以请原谅我在问题中可能犯的任何错误:)

标签: typescriptexpress

解决方案


Express 对继承自 http 版本的请求和响应对象使用自己的原型。

express您可以在对象上找到 Express 响应原型,如express.response.

在普通的 Javascript 中,这将起作用:

const express = require('express');
const app = express();

// add my own method to the response prototype so it can be used
// by any route
express.response.mySend = function(data) {
    // this here is the live res object for this particular request
    console.log("about to send data with my custom response method");
    this.send(data);
}

app.get("/", (req, res) => {
    res.mySend("hello");
});

app.listen(80);

要在 TypeScript 中进行这项工作,您需要为express.response允许您执行此操作的对象进行适当的类型绑定。我不是 TypeScript 人,所以你必须自己承担这部分工作。

仅供参考,请求对象是express.request并且可以类似地使用。


您也可以像这样在中间件中添加自己的方法,但我认为这会稍微降低效率(如果这很重要的话):

const express = require('express');
const app = express();

// add my own method to the response prototype so it can be used
// by any route
app.use((req, res, next) => {
    res.mySend = function(data) {
        // this here is the live res object for this particular request
        console.log("about to send data with my custom response method");
        this.send(data);
    });
    next();
});

app.get("/", (req, res) => {
    res.mySend("hello");
});

app.listen(80);

推荐阅读