首页 > 解决方案 > 如何使用“require”在 NestJS 控制器中导入 JSON?

问题描述

我正在尝试返回一个 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(甚至用打字稿)完成了这个并且工作正常。

我不知道我是否必须设置我的项目来读取 jsons(我是 Nest 的新手)。到现在我已经创建了一个 typescript 文件,它导出了一个带有 json 内容的 const 并且我成功地调用了它

标签: jsontypescriptnestjs

解决方案


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

让我们试试这段代码:

你的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
}

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

让我知道它是否有帮助;)


推荐阅读