【问题标题】:how to call external API to download file using NestJS?如何使用 NestJS 调用外部 API 下载文件?
【发布时间】:2022-01-04 17:49:56
【问题描述】:

我想调用外部 API,然后在我的应用程序中下载 JSON 文件。使用带有 axios 的简单节点 js 项目,我可以执行以下操作。

const fs = require('fs');

const axios = require('axios').default;


axios.get('https://www.nseindia.com/').then(res => {
  return axios.get('https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY', {
    headers: {
      cookie: res.headers['set-cookie'] 
  }
  })
}).then(res => {
  //console.log(res.data);
  let data = JSON.stringify(res.data)
  fs.writeFileSync('../files/option-chain-indices.json',data);
}).catch(err => {
  console.log(err);
})

这会下载文件夹中的文件。

但我不知道,如何使用 NestJs 做到这一点?

【问题讨论】:

  • 为什么不能使用上面的代码?您是特别想使用@nestjs/axios 还是真的只需要以任何可能的方式完成它?你在 Nest 服务器上试过什么?

标签: node.js api nestjs


【解决方案1】:

我相信您需要做的是创建一个服务,将您的示例代码放入一个函数中,然后使用 DI 从控制器或解析器调用该函数到您刚刚创建的服务。

请参阅下面的示例代码以供参考。

import { Injectable } from '@nestjs/common';
import * as fs from "fs";
import * as axios from "axios";
@Injectable()
export class FileService {
  saveFile() {
    return axios
      .get("https://www.nseindia.com/")
      .then((res) => {
        return axios.get(
          "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY",
          {
            headers: {
              cookie: res.headers["set-cookie"],
            },
          }
        );
      })
      .then((res) => {
        //console.log(res.data);
        let data = JSON.stringify(res.data);
        fs.writeFileSync("../files/option-chain-indices.json", data);
        return data;
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

也可以根据 nestjs 文档使用 HttpModule 代替原始 axios。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-06-22
  • 2013-07-25
  • 2012-12-22
  • 2020-04-24
  • 1970-01-01
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多