node.js - 如何使用 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)
}
};
推荐阅读
- android - 如何使用 kotlin 设置网格布局重力
- node.js - 如何在创建后立即查询 S3 存储桶时避免竞争条件?
- android - 如何制作 Firebase ShortDynamicLink Xamarin.Android
- shell - 列出 vCenter powercli 脚本中的空端口组
- flutter - 如何通过 WhatsApp url 共享 csv 文件?
- duplicates - 保存文件时如何附加时间戳而不是数字
- macos - Android Studio 在生成签名的 APK 时试图在 Mac OS 的错误位置找到构建文件夹
- windows - Windows 批处理文件:GOTO、DELAYEDEXPANSION 问题
- javascript - 在定义 Sequelize 模型时运行行查询
- flutter - 显示每月颤振的每个星期的工作日