vue2:统一处理页面跳转链接上的参数整体加密,解密不在页面单独处理
时间: 2024-11-26 07:21:08 浏览: 78
在Vue 2应用中,为了保护页面跳转时传递的敏感信息不被直接暴露,你可以采用整体加密的方式对URL中的参数进行加密,然后只在服务器端进行解密处理。这样可以避免前端代码被恶意查看时直接获取到未加密的数据。
步骤大致如下:
1. **加密函数**:
- 创建一个加密函数,通常可以使用像`crypto-js`这样的库来实现AES加密或Base64编码等操作。
```javascript
import CryptoJS from 'crypto-js';
const encryptParams = (params) => {
let encryptedStr = CryptoJS.AES.encrypt(JSON.stringify(params), 'your-secret-key').toString();
return encryptedStr;
};
```
2. **路由配置**:
- 在Vue Router的`beforeEach`守卫中拦截每次导航,将参数加密后再拼接到URL上。
```javascript
export default new VueRouter({
// ...
beforeEach((to, from, next) => {
if (process.env.NODE_ENV === 'production') {
const encryptedParams = encryptParams(to.query);
to.fullPath = `${to.path}?encryptedParams=${encryptedParams}`;
}
next();
}),
});
```
3. **服务器解密**:
- 当接收到请求到达服务器时,需要在后端(如Node.js、Express等)解析URL,解密加密后的参数。
```javascript
const decryptParams = (encryptedStr, secretKey) => {
try {
const decryptedData = CryptoJS.AES.decrypt(encryptedStr, secretKey).toString(CryptoJS.enc.Utf8);
return JSON.parse(decryptedData);
} catch (e) {
console.error('Failed to decrypt parameters:', e);
}
};
app.use((req, res, next) => {
const encryptedParams = req.query.encryptedParams;
const decryptedParams = decryptParams(encryptedParams, 'your-secret-key');
// 解析并处理解密后的数据
next({ params: decryptedParams });
});
```
阅读全文
相关推荐















