json - 如何使用“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 并且我成功地调用了它
解决方案
- 我想问题在于您导入
.json
文件的方式(更改导入而不是 const) - 另一个建议或解决方案是利用
.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 文件的内容。
让我知道它是否有帮助;)
推荐阅读
- javascript - DynamoDB 数据库查询中的无效参数 - Javascript - AWS
- circleci - 与 CircleCI 并行运行 4 个以上的作业
- bash - 获取分支中提交的提交哈希
- asp.net-mvc - 通过函数传递 shell 脚本
- amazon-web-services - AWS Elastic Beanstalk - 实例之间的共享计数器变量
- r - 在 dplyr 中对多个变量进行累积和
- getstream-io - 如何使用stream_python在own_reactions中获取单个用户的数据?
- php - PHP 输出为空
- next.js - 找不到模块:无法解析 '/snapshot/frontend/node_modules/next-server/dist/lib' 中的 '@babel/runtime-corejs2/core-js/array/is-array'
- python - 重新格式化包含字典的 pandas 数据框