首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用“require”在NestJS控制器中导入JSON?

如何使用“require”在NestJS控制器中导入JSON?
EN

Stack Overflow用户
提问于 2019-12-18 00:33:01
回答 2查看 19.2K关注 0票数 11

我试图返回一个json文件作为控制器响应,但是我无法获得json的内容。

代码语言:javascript
复制
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的类型记录文件时,我成功地将它命名为

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-18 19:01:08

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

让我们尝试使用以下代码:

您的common.controller.ts文件:

代码语言:javascript
复制
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

代码语言:javascript
复制
{
  "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

(如果有帮助,请告诉我;)

票数 20
EN

Stack Overflow用户

发布于 2019-12-18 01:09:31

首先,确保您正确地调用它。

你得到什么回应了吗?如果没有,请检查您的方法名,因为它的拼写如下:getPaymentMoethod,并且应该是:getPaymentMethod

其次,我建议在方法之外要求并将其设置为常量。

最后,尝试将其封装在JSON.stringify()中,以将响应转换为json字符串化对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59383994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档