【问题标题】:how to use exported api endpoint in node and express如何在节点中使用导出的 api 端点并表达
【发布时间】:2020-08-02 00:57:44
【问题描述】:

我试图更好地了解 express 以及它如何使用不同的端点。

我看到了一个读取 json 文件的端点示例。

const fs = require('fs');
const path = require('path');

export default app => {
  app.get('/api/price', (req, res) => {
    fs.readFile(path.resolve(__dirname, './price.json'), (err, resp) => {
      if (err) {
        res.send(400, 'ERROR');
      }

      res.send(resp);
    });
  });
};

然后将其导入到 server.js 文件中,如下所示。如您所见,它是作为价格 api 导入的。

import express from 'express';
import priceApi from './priceapi';
const app = express();

priceApi(app)

app.listen(3000, () => {
  console.log("Listening on PORT 3000");
});

我的问题是如何使用这个 priceApi,特别是 `priceApi(app) 并访问存储在 JSON 文件中的信息并从它在 server.js 中引用的端点的 JSON 文件输出信息?

【问题讨论】:

  • 为什么需要通过express访问./price.json
  • Routes 用于 HTTP 请求。如果你想在你的 javascript 中加载 json 文件,你应该使用一个函数而不是一个路由
  • 如果你访问了 3000 端口,你没有得到数据?
  • 你到底想做什么?读取price.json 的特定部分并通过新端点返回此数据,例如/api/price/details?
  • @eol 是的。我正在使用以这种方式设置的示例项目。被server.js中的priceApi(app)搞糊涂了,不知道怎么用。

标签: javascript node.js express


【解决方案1】:

为了不必在每次请求时都加载文件,请在应用启动期间加载一次 json 文件。然后公开一个新端点并提供 json:

import express from 'express';
import priceApi from './priceapi';
const app = express();
const prices = require('./path/to/prices.json');

app.get('/api/price', (req,res) => {
  res.json(prices); // does not necessarily need to be this, you can also map/filter stuff of the prices-json and only return this data
});

app.listen(3000, () => {
  console.log("Listening on PORT 3000");
});

【讨论】:

  • 我相信 priceApi 就是这样做的。哪个是函数导出默认函数。
  • 在您的代码中没有将下载 json 文件,我的代码会将文件的内容作为 json 内容类型返回,以便将文件加载到内存中一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多