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

标签 node.js nestjs

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

错误:检测到循环依赖

// 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,请尝试将其与maintain compatibility with Nest standard response handlingpassthrough参数一起使用。 .

类似这样的东西(我做了一些重构以使其更干净)

    @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",
            });
        }
    }

p.s.:并尝试使用 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...
    }

关于node.js - 使用 FileInterceptor 上传文件时如何在 NestJs 中返回自定义状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63090505/

相关文章:

Node.js 错误回调

node.js - GraphQL - POST 正文丢失。你忘记使用 body-parser 中间件了吗?

typescript - 如何借助 Automapper (TypeScript) 映射充满不同 DTO 的数组条目?

javascript - 使用 nestjs 和 typeorm 为实体保存审计

javascript - 查询 Node.js、Sequelize 和 Mysql

node.js - Instagram 与 NodeJS 抛出 404 错误

javascript - 使用带有索引变量的 $set 来更新文档

nestjs - bool 查询参数被视为字符串,而不是转换为 bool 数据类型

node.js - NestJS - 在微服务中结合 HTTP 和 RabbitMQ

typescript - 为什么partialType 不使属性可以为空?