在JAM Stack中保护API密钥有多种方法,以下是其中一种解决方案,包含代码示例:
.env
的文件,用于存储API密钥。.env
文件中添加一个变量,例如API_KEY=your-api-key
,将your-api-key
替换为实际的API密钥。process.env
来读取环境变量。示例代码(Node.js):
// 读取环境变量中的API密钥
const apiKey = process.env.API_KEY;
// 使用API密钥进行API调用
fetch('https://api.example.com', {
headers: {
'Authorization': `Bearer ${apiKey}`
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
示例代码(Node.js + Express):
// 读取服务器端环境变量中的API密钥
const apiKey = process.env.API_KEY;
// 使用API密钥进行API调用
app.get('/api/data', (req, res) => {
fetch('https://api.example.com', {
headers: {
'Authorization': `Bearer ${apiKey}`
}
})
.then(response => response.json())
.then(data => res.json(data))
.catch(error => res.status(500).json({ error: 'API调用失败' }));
});
请注意,在使用这些方法时,确保将.env
文件或服务器端环境变量添加到.gitignore
中,以避免将API密钥泄露到源代码管理系统中。同时,确保在生产环境中安全地管理和存储API密钥。
上一篇:保护IoT设备以及TLS