简体   繁体   English

“发送后无法设置标题”-直接设置响应时

[英]“Can't set headers after they are sent” - when setting response directly

I'm using NestJS for my API server and am very satisfied with it. 我将NestJS用于我的API服务器,对此感到非常满意。 Most of my controller functions are calling async functions and return JSON - works like a charm. 我的大多数控制器函数都在调用异步函数并返回JSON-就像一个魅力。

But in some controller functions, i need to set the response/headers/etc directly to the response object, eg: 但是在某些控制器功能中,我需要直接将响应/标头/等设置为响应对象,例如:

@Get('api/media')
async getMedia(@Param('id') id: string,
               @Req() req) {
    let result = await getMediaFromBackend(id);
    req.res.set('Content-Type', result.contentType); // need to set content-type dynamically
    req.res.send(result.data); // send non-json response
}

In some other case i need to pipe a gzipStream. 在其他情况下,我需要管道gzipStream。

It works, but i'm always getting an unhandled rejection in the console: 它有效,但是我总是在控制台中遇到未处理的拒绝:

"Can't set headers after they are sent" “发送后无法设置标题”

Seems like NestJS wants to set/overwrite Headers after the controller function returns. 似乎NestJS想要在控制器函数返回后设置/覆盖标头。 Any ideas how to avoid this? 任何想法如何避免这种情况? I would need some functionality to tell NestJS like "im taking full care of the response myself" 我需要一些功能来告诉NestJS,例如“我自己会完全照顾好响应”

Thanks a lot! 非常感谢!

Because you're injecting @Req() and access the response via req.res the standard nest controller behavior is used. 因为要注入@Req()并通过req.res访问响应, req.res了标准的嵌套控制器行为。 If you directly use @Res instead nest won't mess with the response object and you have full control over it. 如果直接使用@Res则nest不会与响应对象@Res ,您可以完全控制它。

@Get('api/media')
async getMedia(@Param('id') id: string,
               @Res() res) {
    let result = await getMediaFromBackend(id);
    res.set('Content-Type', result.contentType); // need to set content-type dynamically
    res.send(result.data); // send non-json response
}

Caution! 警告! This means interceptors, exception filters etc. won't work for this route. 这意味着拦截器,异常过滤器等不适用于此路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM