保护NodeJS RESTful API和React客户端应用涉及以下几个方面的解决方法:
NodeJS API示例:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: 'http://localhost:3000', // 允许访问的域名
optionsSuccessStatus: 200 // 返回成功状态码
}));
// API路由和处理逻辑
// ...
app.listen(8000, () => {
console.log('API server started on port 8000');
});
React客户端示例:
fetch('http://localhost:8000/api/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:8000' // 允许访问的域名
}
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
NodeJS API示例:
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
// 模拟用户登录
app.post('/api/login', (req, res) => {
// 验证用户名和密码
const { username, password } = req.body;
// ...
// 生成访问令牌
const token = jwt.sign({ username }, 'secret_key');
res.json({ token });
});
// 验证令牌
app.use((req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}
try {
const decoded = jwt.verify(token, 'secret_key');
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ message: 'Invalid token' });
}
});
// API路由和处理逻辑
// ...
app.listen(8000, () => {
console.log('API server started on port 8000');
});
React客户端示例:
fetch('http://localhost:8000/api/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}` // 添加访问令牌
}
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
NodeJS API示例:
const express = require('express');
const xss = require('xss');
const app = express();
// 在处理请求之前对用户输入进行过滤
app.use((req, res, next) => {
req.body = xss(req.body);
next();
});
// API路由和处理逻辑
// ...
app.listen(8000, () => {
console.log('API server started on port 8000');
});
React客户端示例:
// 在使用用户输入前对其进行转义
const userInput = '';
const escapedInput = escape(userInput);
console.log(escapedInput);
以上是保护NodeJS RESTful API和React客户端应用的一些解决方法,具体实现还需要根据具体需求和安全要求进行调整和完善。