简体   繁体   English

如何在节点和快递中使用导出的 api 端点

[英]how to use exported api endpoint in node and express

I am trying to get a better understanding of express and how it uses different end points.我试图更好地理解 express 以及它如何使用不同的端点。

I saw an example of an endpoint which reads in a json file being used like this.我看到一个端点示例,它读取 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);
    });
  });
};

it is then imported in a server.js file like the following.然后将其导入到 server.js 文件中,如下所示。 As you can see it is imported as price api.如您所见,它以 api 的价格导入。

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

priceApi(app)

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

My question is how do I use this priceApi so in particular `priceApi(app)and access the information stored in the JSON file and output information from the JSON file that the endpoint it is referring to in server.js?我的问题是我如何使用这个 priceApi,特别是 `priceApi(app) 并访问存储在 JSON 文件和 output 信息中的 Z0ECD11C1D7A287401D148A23BBD7 信息,它是指服务器中的端点。

In order to not having to load the file on every request, load the json file once during startup of your app.为了不必在每次请求时都加载文件,请在应用程序启动期间加载一次 json 文件。 Then expose a new endpoint and serve the 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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM