首页 > 解决方案 > 如何使用 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 文件中的值

标签: node.jsexpresssecret-key

解决方案


您始终可以在节点代码中使用 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)
    }

};



推荐阅读