如何将变量传递给端点nodejs

How to pass variable to endpoint nodejs

我有 2 个端点。

  1. 它是: a) 从客户端接收数据 b) + 保存到文件 c) + 统计保存了多少次数据。
    app.post('/api/v1', (req,res) => {

      var data = req.body;
      console.log(req.body)

      const storeData = (data, path) => {
        try {
          console.log("Uploading data to file...")
          fs.appendFileSync(path, JSON.stringify(data))
          counter = counter +1;
          console.log(counter);
        } catch (err) {
          console.error(err)
        }
      }
    storeData(data,'./files/data.json');
  1. 它是: a) 向客户端发送数据
app.get('/api/counter', (req, res) => {
  res.status(200).send({

  })
});

我的问题是:

“如何修改第二个端点以从第一个端点获取计数器并将其发送给客户端?

您基本上是在要求一个简单的状态管理模块。

我建议使用全局计数器来存储计数。增加第一个端点中的计数器,然后在第二个端点中访问相同的计数器。或者为其设置外部状态管理 - 将计数器存储在文件系统或数据库中(不推荐)

var counter;

function setCount(num=0){
    counter = num;
}

function inc(){
    counter++;
}

function getCount(){
    return counter;
}

module.exports = {
    inc: inc,
    setCount: setCount,
    getCount: getCount
};

在你的文件中有 API 个端点

const arb = require('./path/name_of_your_arbitrary_file');

...
// Increment in 1st endpoint
arb.inc();

...
// Get Count in 2nd endpoint
var count = arb.getCount();