如何使用 node 和 express 更新秘密

问题描述

我正在开发一个节点、express 和 React 应用程序。我正在使用一些外部 API 数据,但 API 令牌每 24 小时过期一次。首先,我将其保存在 .env 文件中,但我不能只更新该值并使用它来重新发送我的请求和新令牌。 有没有什么好方法可以让我以编程方式更新这个秘密(每次我的请求失败并显示特定错误消息时),立即使用它而无需重新启动服务器并在接下来的 24 小时内继续使用它,直到我必须重复这个过程?如果这是不可能的,那么最好的方法是什么?

这是我尝试更新它的方式

module.exports = async function (req,res,next) {
    const config = {
        headers: {
            "Accept": "application/json","api-token": process.env.GEO_API_KEY,"user-email": process.env.GEO_API_EMAIL
        }
    }
    try {

        const { data } = await axios.get('url',config);

        if (data.auth_token) {
            process.env['GEO_API_AUTH_TOKEN'] = data.auth_token;
        }

    } catch (error) {
        console.error(error)
    }

};

但这不会更新 .env 文件中的值

解决方法

您始终可以在节点代码中使用 bash 命令。 这是一个使用 sed 的例子。这适用于大多数 *nix 机器。


const { exec } = require('child_process');



module.exports = async function (req,res,next) {
    const config = {
        headers: {
            "Accept": "application/json","api-token": process.env.GEO_API_KEY,"user-email": process.env.GEO_API_EMAIL
        }
    }
    try {

        const { data } = await axios.get('url',config);

        if (data.auth_token) {




            exec(`sed -i "" "s/${oldAPIkey}/${data.auth_token}/" .env`,(err,stdout,stderr) => {
              if (err) {
                // node couldn't execute the command
                return;
            }

          // the *entire* stdout and stderr (buffered)
          console.log(`stdout: ${stdout}`);
          console.log(`stderr: ${stderr}`);
          
          //update them in the process so you don't have to restart your app if you want.

          process.env['GEO_API_AUTH_TOKEN'] = data.auth_token;


      });
        }

    } catch (error) {
        console.error(error)
    }

};


,

您可以尝试使用一些辅助变量。当服务器启动时,这个 var 将设置为 process.env.GEO_API_KEY,然后您可以随着时间的推移设置新值:

let apiToken = process.env.GEO_API_KEY;

module.exports = async function (req,next) {
  const config = {
    headers: {
      "Accept": "application/json","api-token": apiToken,"user-email": process.env.GEO_API_EMAIL
    }
  }

  try {

    const { data } = await axios.get('url',config);

    if (data.auth_token) {
        apiToken = data.auth_token;
    }

  } catch (error) {
    console.error(error)
  }
};