我试图返回一个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'和应用程序没有编译
我用快件(甚至打字本)做了这件事,而且工作得很好。
我不知道我是否需要设置我的项目来阅读jsons (我是nest的newby )。当我创建了一个带有json内容的const的类型记录文件时,我成功地将它命名为
发布于 2019-12-18 19:01:08
.json文件的方式(更改导入而不是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
}最后的想法:您可以使用res对象的res方法,这取决于您想要发送json文件的json 文件还是json文件的content。
(如果有帮助,请告诉我;)
发布于 2019-12-18 01:09:31
首先,确保您正确地调用它。
你得到什么回应了吗?如果没有,请检查您的方法名,因为它的拼写如下:getPaymentMoethod,并且应该是:getPaymentMethod。
其次,我建议在方法之外要求并将其设置为常量。
最后,尝试将其封装在JSON.stringify()中,以将响应转换为json字符串化对象。
https://stackoverflow.com/questions/59383994
复制相似问题