如何使用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, res, 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)
}
};

最新更新