Dan*_*iaz 5 json typescript nestjs
我试图返回一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)
实际上日志返回:
Error: Cannot find module './data/payment-method'并且应用程序没有编译
我已经用 express(即使是打字稿)完成了这项工作,并且工作正常。
我不知道我是否必须设置我的项目来读取 jsons(我是 nest 的新手)。到目前为止,我已经创建了一个 typescript 文件,它导出了一个带有 json 内容的常量,并且我成功地调用了它
A. *_*tre 11
.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
}
}
Run Code Online (Sandbox Code Playgroud)
同样在您的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
}
Run Code Online (Sandbox Code Playgroud)
最后的想法:您可以使用对象的sendfile()方法,res具体取决于您是要发回 json文件还是json文件的内容。
如果有帮助,请告诉我;)
| 归档时间: |
|
| 查看次数: |
8509 次 |
| 最近记录: |