繁体   English   中英

使用 FileInterceptor 上传文件时如何在 NestJs 中返回自定义状态码?

[英]How to return custom status codes in NestJs while using FileInterceptor to upload a file?

我正在尝试为不同类型的异常返回自定义状态代码。 尽管我收到了正确的响应,但我无法做到这一点而不会导致错误。 该错误仅发生在if 条件块内(如果我在 post 请求中发送文件)。 else 块中没有错误

错误:检测到循环依赖

// Below code gives this error =>  Error: cyclic dependency detected

import { Controller, Post, Req, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Request, Response } from 'express';

@Controller('testing')
export class TestController {
    constructor() { }

    @Post('/upload')
    @UseInterceptors(FileInterceptor('file'))
    upload(@UploadedFile() file, @Res() response: Response) { 
        if (file && file !== undefined) {
            return response.status(200).json({
                status: "OK",
                message: "File Uploaded"
            });
        } else {
            return response.status(400).json({
                status: "BAD REQUEST",
                message: "File not found"
            });
        }
    }
}

不久前我遇到了类似的错误。

如果您真的想使用@Res ,请尝试将其与passthrough参数一起使用,以 保持与 Nest 标准响应处理的兼容性。

像这样的东西(我做了一些重构使它更干净一些)

    @Post("/upload")
    @UseInterceptors(FileInterceptor("file"))
    upload(@UploadedFile() file, @Res({ passthrough: true }) res: Response) {
        if (file) {
            res.status(HttpStatus.OK).json({
                status: "OK",
                message: "File uploaded",
            });
        } else {
            res.status(HttpStatus.BAD_REQUEST).json({
                status: "BAD REQUEST",
                message: "File not found",
            });
        }
    }

ps:并尝试使用HttpStatus枚举来使您的代码更具可读性

但是有一个更好更干净的解决方案。 如果文件不存在,你只需要抛出一个BadRequestException和你想要的消息,NestJS 会神奇地为你处理一切 =D

    @Post("/upload")
    @HttpCode(HttpStatus.OK)
    @UseInterceptors(FileInterceptor("file"))
    upload(@UploadedFile() file) {
        if (!file) {
            throw new BadRequestException("File not found!");
        }
        // do something with the file...
    }

暂无
暂无

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

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