首页 > 解决方案 > 如何使用express在回调函数之间传递值?

问题描述

我正在尝试文档附带的快速路由处理程序以特定顺序进行一系列函数调用,所以我想从cb0to cb1(或cb2)传递一个值,目前我正在req对象中设置一个属性并访问它从另一个处理程序,这工作正常。

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

const cb0 = function (req, res, next) {
  console.log('CB0');
  req.cb0val = 'Hello';
  next();
}

const cb1 = function (req, res, next) {
  console.log('CB1');
  req.cb1val = 'World';
  next();
}

const cb2 = function (req, res) {
  res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
}

app.get('/', [cb0, cb1, cb2])

app.listen(PORT, () => {
  console.log(`⚡️[server]: Server is running at https://localhost:${PORT}`);
});

使用时出现问题typescript

import express from 'express';
const app = express();
const PORT = 8000;

const cb0: express.RequestHandler = function (req: express.Request, res: express.Response, next: Function) {
  console.log('CB0');
  req.cb0val = 'Hello';
  next();
}

const cb1: express.RequestHandler = function (req: express.Request, res: express.Response, next: Function) {
  console.log('CB1');
  req.cb1val = 'World';
  next();
}

const cb2: express.RequestHandler = function (req: express.Request, res: express.Response) {
  res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
}

app.get('/example/c', [cb0, cb1, cb2])

app.listen(PORT, () => {
  console.log(`⚡️[server]: Server is running at https://localhost:${PORT}`);
});

因为我正在设置类型,req因为express.Request我无法设置该类型的新属性,所以会出现以下错误:

index.ts:7:7 - error TS2339: Property 'cb0val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

7   req.cb0val = 'Hello';
        ~~~~~~
index.ts:13:7 - error TS2339: Property 'cb1val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

13   req.cb1val = 'World';
         ~~~~~~
index.ts:18:24 - error TS2339: Property 'cb0val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

18   res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
                          ~~~~~~
index.ts:18:38 - error TS2339: Property 'cb1val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

18   res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
                                        ~~~~~~

express.Request在不更改to类型的情况下处理这种情况的正确方法是any什么?

标签: typescriptexpress

解决方案


你可以使用一种叫做声明合并的东西。

express.d.ts在项目中的某处创建一个名为的文件。这通常在@types项目根目录的文件夹中创建 ( @types/express.d.ts)。

这个文件的内容应该是

declare namespace Express {
    interface Request {
        cb0val: string
        // other custom properties ...
    }
}

在您的 tsconfig 中,设置一个typeRoot或将新文件添加到该types字段。

"typeRoots": [
  "@types/",
  "node_modules/@types/"
]

推荐阅读