我希望将摩根·博迪设置为记录请求和响应的中间件。
所以我创建了一个这样的函数:
export function RequestLogging(app) {
const logger = new Logger('Request');
app.use(
morganBody(app, {
stream: { // <--- error is here "Void function return value is used "
write: (message) => logger.log(message.replace('\n', '')),
},
}),
);
}我去拜访main.ts
// main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
useRequestLogging(app);
// ...
}然而,这似乎不起作用。我在网上发现了一个错误'Void function return value is used',stream: {
知道怎么修吗?
更新:
我尝试走不同的路径,实际上只需按照main.ts文档的要求将main.ts插入:
import bodyParser from 'body-parser';
import morganBody from 'morgan-body';
app.use(bodyParser.json());
// hook morganBody to express app
morganBody(app); <-- getting error here "TS2345: Argument of type 'INestApplication' is not assignable to parameter of type 'Application'."我希望有一个适当的文档如何在nestjs中进行处理。
发布于 2021-08-21 00:41:39
这是一个非常有趣的中间件。它最终需要表达式实例本身,因为它在幕后调用app.use(morgan)和app.response.send()。我会研究一些其他的解决方案,而不是以这种方式访问响应的东西。
无论哪种方式:这个设置都是有效的。
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import * as morgan from 'morgan-body';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const logger = app.get(Logger);
(morgan as any)(app.getHttpAdapter().getInstance(), {
stream: {
write: (message: string) => {
logger.log(message.replace('\n', ''));
return true;
},
},
});
await app.listen(3033);
}
bootstrap();包的类型也是错误的,它不是默认的导出,而是一个命名的导出,因此import morgan from 'morgan-body'不能像广告中所宣传的那样工作(至少对我来说不是这样)。
return true是必要的,因为write需要一个具有布尔值的stream.writable()方法。您可以将此默认为true。然后,您必须使用app.getHttpAdapter().getInstance(),以确保将express实例传递给中间件。再一次,错误的设置,但它是有效的。
https://stackoverflow.com/questions/68864040
复制相似问题