保护 Node.js API 的方法有很多种,下面给出两种常见的解决方案以及相应的代码示例:
使用 API 密钥进行身份验证:
代码示例:
// 客户端请求 API
const apiKey = 'your-api-key';
const url = 'http://example.com/api';
const headers = { 'Authorization': `Bearer ${apiKey}` };
fetch(url, { headers })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// 服务器端验证 API 密钥
const express = require('express');
const app = express();
const validApiKeys = ['your-api-key'];
app.get('/api', (req, res) => {
const apiKey = req.headers.authorization.replace('Bearer ', '');
if (validApiKeys.includes(apiKey)) {
// 执行 API 逻辑
res.json({ message: 'API request successful' });
} else {
res.status(401).json({ error: 'Invalid API key' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
使用 JSON Web Tokens (JWT) 进行身份验证:
代码示例:
// 客户端请求 API
const jwt = 'your-jwt';
const url = 'http://example.com/api';
const headers = { 'Authorization': `Bearer ${jwt}` };
fetch(url, { headers })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// 服务器端验证 JWT
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
const secretKey = 'your-secret-key';
app.get('/api', (req, res) => {
const token = req.headers.authorization.replace('Bearer ', '');
try {
const decoded = jwt.verify(token, secretKey);
// 执行 API 逻辑
res.json({ message: 'API request successful', user: decoded.user });
} catch (error) {
res.status(401).json({ error: 'Invalid JWT' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
请注意,以上代码示例仅用于演示目的,实际应用中可能需要根据具体业务需求进行适当的修改和改进。