我试图返回一个 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)完成了这个并且工作正常。
我不知道是否必须设置我的项目来读取json(我是nest的新手)。到目前为止,我已经创建了一个 typescript 文件,导出带有 json 内容的 const,并且我成功地调用了它
.json
文件的方式(更改 import 而不是 const).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
}
最后的想法:您可以使用
sendfile()
对象的 res
方法,具体取决于您是否要发回 json file 或 json 文件的 content。
如果有帮助请告诉我;)
首先确保您正确调用它。
您收到任何回复了吗?如果没有,请仔细检查您的方法名称,因为它的拼写如下:
getPaymentMoethod
,它应该是这样:getPaymentMethod
。
其次,我建议在方法之外进行 require 并将其设置为常量。
最后尝试将其包装在
JSON.stringify()
中以将响应转换为 json 字符串化对象
我找到了类似错误的解决方案,关键在于导入,基本上类似于 require 的东西是使用语法 import * as variable from '/replace-with-your-path' 导入。解释如下:
使用 import * 导入:
typescript
import * as data1 from './data.json';
console.log(data1); // Prints the content of the data.json file as an object
With this method, data1 is an object containing the entire content of the JSON file.
导入而不导入*为:
typescript
import data2 from './data.json';
console.log(data2); // Error: Module './data.json' not found
使用此方法,TypeScript 期望文件采用模块格式,这意味着它期望默认对象而不是整个 JSON 文件内容。但由于我们的 data.json 文件不导出默认对象,TypeScript 会抛出错误。