【问题标题】:How to use 'require' to import a JSON in NestJS controller?如何使用“require”在 NestJS 控制器中导入 JSON?
【发布时间】:2020-04-10 12:46:17
【问题描述】:

我正在尝试返回一个 json 文件作为控制器响应,但我无法获取 json 的内容。

import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';
import { Response } from 'express';

import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file is imported fine
const MOCKED_RESPONSE = require('./data/payment-method-mock'); // this json file is not found

@Controller('commons')
export class CommonController {

@Get('/payment-method')
  getPaymentMoethod(@Res() res: Response): any {
    res.status(HttpStatus.OK).send(MOCKED_RESPONSE);
  }

}

实际上日志返回:Error: Cannot find module './data/payment-method' 并且应用程序没有编译

我已经使用 express(甚至使用 typescript)完成了这项工作,并且工作正常。

我不知道我是否必须设置我的项目来读取 jsons(我是 Nest 新手)。到目前为止,我已经创建了一个 typescript 文件,该文件导出了一个带有 json 内容的 const,并且我成功地将其命名为

【问题讨论】:

  • 你得到了什么?

标签: json typescript nestjs


【解决方案1】:
  1. 我猜问题在于您导入.json 文件的方式(更改导入而不是const)
  2. 另一个建议或解决方案是利用 res 对象(实际上是 express 适配器响应对象)的 .json() 方法。

让我们试试这段代码:

您的common.controller.ts 文件:

import { Controller, Get, Res, HttpStatus, Query } from '@nestjs/common';
import { Response } from 'express';

import * as MOCKED_RESPONSE_TS from './data/payment-method.data'; // this ts file should still be imported fine
import * as MOCKED_RESPONSE from './data/payment-method-mock.json'; // or use const inside the controller function

@Controller('commons')
export class CommonController {

@Get('/payment-method')
  getPaymentMoethod(@Res() res: Response): any {
    res.status(HttpStatus.OK).json(MOCKED_RESPONSE); // <= this sends response data as json
  }
}

在您的tsconfig.json 文件中,别忘了添加这一行:

tsconfig.json

{
  "compilerOptions": {
    // ... other options 

    "resolveJsonModule": true, // here is the important line, this will help VSCode to autocomplete and suggest quick-fixes

    // ... other options
}

最后的想法:您可以使用res 对象的sendfile() 方法,具体取决于您是要发回json 文件 还是 内容你的 json 文件。

如果有帮助,请告诉我;)

【讨论】:

  • 这有助于 VSCode 自动完成,然后我在 require 函数行中得到了一个关于更改导入而不是 const 的 VSCode...谢谢
  • 我编辑了你的答案,查看它,以便我可以选择它作为解决方案
【解决方案2】:

首先确保您正确调用它。

您是否收到任何回应?如果不仔细检查您的方法名称,因为它的拼写如下:getPaymentMoethod,它应该是:getPaymentMethod

其次,我建议在方法之外要求并将其设置为常量。

最后尝试将其包装在 JSON.stringify() 中,以将响应转换为 json 字符串化对象

【讨论】:

  • 我相信在nest中控制器函数的名称只是供开发者参考;我在 require 节点函数中有一个系统错误,它破坏了流程:(
  • 跟随我评论的第二步。需要在函数之外。它应该在全局状态的控制器的最顶端
  • 在文件顶部设置 require 会导致应用崩溃并且无法编译...有趣
猜你喜欢
  • 1970-01-01
  • 2021-01-01
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2021-02-11
  • 2021-10-20
  • 2015-05-27
相关资源
最近更新 更多