十三、安全最佳实践
13.1 XSS 防护
// 错误:直接插入 HTML
element.innerHTML = userInput; // 危险!
// 正确:转义 HTML
function escapeHtml(str) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
element.textContent = userInput; // 自动转义
// 使用 DOMPurify 库
import DOMPurify from "dompurify";
const clean = DOMPurify.sanitize(userInput);
element.innerHTML = clean;
13.2 CSRF 防护
// 使用 CSRF Token
fetch("/api/data", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken
},
credentials: "same-origin" // 携带 Cookie
});
// 设置 Cookie 属性
document.cookie = "sessionId=xxx; SameSite=Strict; Secure; HttpOnly";
13.3 敏感信息保护
// 不在前端存储敏感信息
// 错误:localStorage.setItem("password", "123456");
// 使用 HTTPS
// 避免在 URL 中传递敏感数据
// 错误:https://example.com?password=123
// 使用 Content Security Policy (CSP)
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
// 避免使用 eval()
// 错误:eval(userInput);
// 使用 JSON.parse 替代 eval
const data = JSON.parse(validatedJson);
十四、调试与测试
14.1 调试技巧
// console 方法
console.log("普通日志");
console.error("错误信息");
console.warn("警告信息");
console.info("信息");
console.debug("调试信息");
console.table([
{ name: "张三", age: 25 },
{ name: "李四", age: 30 }
]); // 表格形式
console.group("分组");
console.log("内容1");
console.log("内容2");
console.groupEnd();
console.time("计时");
// 代码块
console.timeEnd("计时"); // 输出执行时间
console.trace(); // 输出调用栈
// 断点调试
debugger; // 代码执行到这里会暂停
// 条件断点
if (condition) {
debugger;
}
// 性能分析
console.profile("性能分析");
// 要分析的代码
console.profileEnd();
14.2 单元测试
// 使用 Jest 测试
// math.js
export function add(a, b) {
return a + b;
}
// math.test.js
import { add } from "./math";
test("add 函数应该正确相加", () => {
expect(add(2, 3)).toBe(5);
expect(add(-1, 1)).toBe(0);
expect(add(0, 0)).toBe(0);
});
// 异步测试
test("异步请求应该成功", async () => {
const data = await fetchData();
expect(data).toHaveProperty("id");
});
// Mock 函数
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
expect(mockFn()).toBe(42);
十五、浏览器兼容性与构建工具
15.1 Babel 转译
// .babelrc 配置
{
"presets": [
["@babel/preset-env", {
"targets": "> 0.25%, not dead",
"useBuiltIns": "usage",
"corejs": 3
}]
]
}
// 编译前(ES6+)
const arrow = () => console.log("Hello");
const promise = Promise.resolve();
// 编译后(ES5)
var arrow = function arrow() {
return console.log("Hello");
};
var promise = Promise.resolve();
15.2 Polyfill
// 按需引入 polyfill
import "core-js/stable/array/from";
import "core-js/stable/promise";
// 使用 @babel/preset-env 自动注入
// 检查特性支持
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement) {
return this.indexOf(searchElement) !== -1;
};
}
JavaScript 的世界广阔而深邃,愿这系列文章成为你技术之路上的重要参考。持续学习,不断实践,你一定能成为优秀的 JavaScript 开发者!
来源:
https://app-abdss1rim1oh.appmiaoda.com