如何使用express在回调函数之间传递值? [复制]
Posted
技术标签:
【中文标题】如何使用express在回调函数之间传递值? [复制]【英文标题】:How to pass a value between callback functions using express? [duplicate] 【发布时间】:2021-02-15 11:49:41 【问题描述】:我正在尝试文档附带的express route handlers 以特定顺序进行一系列函数调用,所以我想将一个值从cb0
传递给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
的类型更改为any
的情况下,处理这种情况的正确方法是什么?
【问题讨论】:
【参考方案1】:你可以使用一种叫做声明合并的东西。
在项目的某处创建一个名为express.d.ts
的文件。这通常在项目根目录 (@types/express.d.ts
) 的 @types
文件夹中创建。
这个文件的内容应该是
declare namespace Express
interface Request
cb0val: string
// other custom properties ...
在您的 tsconfig 中,设置 typeRoot
或将新文件添加到 types
字段。
"typeRoots": [
"@types/",
"node_modules/@types/"
]
【讨论】:
以上是关于如何使用express在回调函数之间传递值? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
什么文档描述了传递给 express app.METHOD 回调参数的内容