代码编写安全相关

2021-03-17  本文已影响0人  浅忆_0810

1. 发起请求URL中的拼接参数进行encodeURIComponent编码

// 例子
axios.get(`/news/${encodeURIComponent(id)}`).then(res => {})

2. 在tsconfig.json中添加相关规则

{
  "noImplicitAny": true, // 启用强类型检查
  "noImplicitReturns": true // 确保所有的方法都有返回值
}

3. for-in注意事项

for-in.png

使用 for in循环遍历对象的属性时,对象的属性以及原型链上的所有属性都将被访问

解决方法:

// 方法一
for (const key in value) {
  if (value.hasOwnProperty(key)) {
    // 逻辑处理
  }
}

原理:迭代对象的所有属性,包括它的原型链中的属性,使用object.prototype.hasownProperty方法,该方法返回一个布尔值,指示该属性是否是对象自己的(不是继承的)属性,以过滤继承的属性

// 方法二
for (const key of Object.keys(value)) {
  // 逻辑处理
}

原理:使用object.keys方法,该方法返回给定对象自己的可枚举属性的数组


4. 在tslint.json中配置了每行最大长度(如 120)

// tslint.json
{
  "rules": {
    "max-line-length": [
      true, 
      {
        "limit": 120,
        "check-strings": true, // 是否检查 字符串
        "ignore-pattern": "^import [^,]+ from" // 忽略长导入
      }
    ]
  } 
}
{
  test: 'Iterates through all the attributes of an object, including those in its prototype chain.'
}

// 可使用 转义 符号来进行字符串分割
{
  test: 'Iterates through all the attributes of an object, \
including those in its prototype chain.'
}
上一篇下一篇

猜你喜欢

热点阅读