typescript - 如何使用express在回调函数之间传递值?
问题描述
我正在尝试文档附带的快速路由处理程序以特定顺序进行一系列函数调用,所以我想从cb0
to 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
什么?
解决方案
你可以使用一种叫做声明合并的东西。
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/"
]
推荐阅读
- c# - 错误内部异常时如何在更新条目时忽略错误记录以获取详细信息
- android - 为什么带有分页的recyclerview不能正常工作?
- react-native - 启动 Android Studio 任务时出现 React-Native 错误:app:compileDebugJavaWithJavac FAILED
- reactjs - 在反应中使用antd组件时出错
- ios - 如何在 iOS Swift 运行时更改 AccessibilityLabel?
- hugo - Hugo - 仅输出更改的文件
- python - django-import-export 中的外键
- javascript - 显示由 url 显示的网页的特定部分 (GUI)
- vue.js - 从菜单传递页面 id
- java - 如何将自定义 HTML 文件从 Springfox 2.7.0 迁移到 2.9.2?