记录学习与后端知识并分享学习代码过程(会飞的鱼Blog)

浏览器兼容性问题解决方案

会飞的鱼 0 0 2026年7月10日

浏览器兼容性问题解决方案

日志系统设计

const winston = require('winston')

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
})

if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }))
}

logger.info('信息日志')
logger.warn('警告日志')
logger.error('错误日志')

安全防护方案

// XSS防护
function escapeHtml(str) {
  const div = document.createElement('div')
  div.textContent = str
  return div.innerHTML
}

// SQL注入防护 - 使用参数化查询
const sql = 'SELECT * FROM users WHERE id = ?'
db.query(sql, [userId])

// CSRF防护
const csrfToken = document.querySelector('meta[name="csrf-token"]').content
fetch('/api/data', {
  method: 'POST',
  headers: {
    'X-CSRF-Token': csrfToken
  }
})

// 密码加密
const bcrypt = require('bcrypt')
const saltRounds = 10
const hash = bcrypt.hashSync(password, saltRounds)

单元测试示例

// 使用 Jest
function sum(a, b) {
  return a + b
}

function multiply(a, b) {
  return a * b
}

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3)
})

test('multiply 2 * 3 to equal 6', () => {
  expect(multiply(2, 3)).toBe(6)
})

// 异步测试
test('async test', async () => {
  const data = await fetchData()
  expect(data).toBe('peanut butter')
})

性能优化方案

// 图片懒加载
const images = document.querySelectorAll('img[data-src]')
const imageObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target
      img.src = img.dataset.src
      imageObserver.unobserve(img)
    }
  })
})
images.forEach(img => imageObserver.observe(img))

// 代码分割
const Home = () => import('./Home.vue')
const About = () => import('./About.vue')

// 防抖节流
function debounce(fn, delay) {
  let timer = null
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), delay)
  }
}

API接口设计

// RESTful API 设计
const express = require('express')
const router = express.Router()

// 获取用户列表
router.get('/users', async (req, res) => {
  const { page = 1, pageSize = 10 } = req.query
  // ... 查询逻辑
  res.json({
    code: 0,
    message: 'success',
    data: {
      list: [],
      total: 0,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    }
  })
})

// 创建用户
router.post('/users', async (req, res) => {
  // ... 创建逻辑
  res.json({ code: 0, message: '创建成功' })
})

// 更新用户
router.put('/users/:id', async (req, res) => {
  // ... 更新逻辑
  res.json({ code: 0, message: '更新成功' })
})

// 删除用户
router.delete('/users/:id', async (req, res) => {
  // ... 删除逻辑
  res.json({ code: 0, message: '删除成功' })
})

Nginx配置

server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.html index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}

技术分享,欢迎评论区交流讨论。

本文由 @会飞的鱼 于 2026-7-10 发布在 会飞的鱼Blog,如无特别说明,本博文章均为原创,转载请保留出处。

网友评论

    暂无评论

会飞的鱼 在线咨询

在线时间:9:00-22:00
周六、周日:14:00-22:00