← Назад к вопросам

Как сервер вернет ответ на запрос если ему не нравится CORS?

1.8 Middle🔥 171 комментариев
#Браузер и сетевые технологии

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI3 апр. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Темизация сайта: светлая и тёмная тема

Реализация переключения между светлой и тёмной темой в современном веб приложении.

Способ 1: CSS переменные (рекомендуется)

:root {
  --bg-primary: #ffffff;
  --text-primary: #000000;
  --bg-secondary: #f5f5f5;
  --border-color: #e0e0e0;
}

[data-theme="dark"] {
  --bg-primary: #1e1e1e;
  --text-primary: #ffffff;
  --bg-secondary: #2d2d2d;
  --border-color: #444444;
}

body {
  background-color: var(--bg-primary);
  color: var(--text-primary);
  transition: background-color 0.3s ease;
}

.card {
  background-color: var(--bg-secondary);
  border: 1px solid var(--border-color);
}

React компонент для переключения темы

import { createContext, useContext, useEffect, useState } from 'react'

const ThemeContext = createContext()

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState(() => {
    // Проверить сохранённую тему
    if (typeof window !== 'undefined') {
      return localStorage.getItem('theme') || 'light'
    }
    return 'light'
  })

  useEffect(() => {
    // Применить тему в DOM
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('theme', theme)
  }, [theme])

  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light')
  }

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  )
}

export function useTheme() {
  return useContext(ThemeContext)
}

Компонент переключателя

export function ThemeToggle() {
  const { theme, toggleTheme } = useTheme()

  return (
    <button onClick={toggleTheme} className="theme-toggle">
      {theme === 'light' ? '🌙 Dark' : '☀️ Light'}
    </button>
  )
}

Использование в приложении

import { ThemeProvider } from '@/contexts/ThemeContext'

export default function App() {
  return (
    <ThemeProvider>
      <Header />
      <Main />
      <Footer />
    </ThemeProvider>
  )
}

Способ 2: Tailwind CSS с темой

// tailwind.config.js
export default {
  darkMode: 'class',
  theme: {
    extend: {
      colors: {
        surface: {
          light: '#ffffff',
          dark: '#1e1e1e'
        },
        text: {
          light: '#000000',
          dark: '#ffffff'
        }
      }
    }
  }
}
// Компонент с Tailwind
export function Card() {
  return (
    <div className="bg-white dark:bg-gray-900 text-black dark:text-white p-4">
      Содержание
    </div>
  )
}

Способ 3: Система дизайна

const themes = {
  light: {
    primary: '#0066cc',
    background: '#ffffff',
    text: '#000000',
    border: '#e0e0e0'
  },
  dark: {
    primary: '#3399ff',
    background: '#1e1e1e',
    text: '#ffffff',
    border: '#444444'
  }
}

export function useThemeColors() {
  const { theme } = useTheme()
  return themes[theme]
}

Обнаружение системной темы

export function useSystemTheme() {
  const [systemTheme, setSystemTheme] = useState(() => {
    if (typeof window !== 'undefined') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches
        ? 'dark'
        : 'light'
    }
    return 'light'
  })

  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handler = (e) => {
      setSystemTheme(e.matches ? 'dark' : 'light')
    }
    
    mediaQuery.addEventListener('change', handler)
    return () => mediaQuery.removeEventListener('change', handler)
  }, [])

  return systemTheme
}

Плавный переход без моргания

export function ThemeScript() {
  return (
    <script
      dangerouslySetInnerHTML={{
        __html: `
          (function() {
            const theme = localStorage.getItem('theme') || 'light'
            document.documentElement.setAttribute('data-theme', theme)
          })()
        `
      }}
    />
  )
}

// Добавить в _document.tsx
export default function Document() {
  return (
    <Html>
      <Head>
        <ThemeScript />
      </Head>
      <body>
        <Main />
      </body>
    </Html>
  )
}

Полный пример с Tailwind

'use client'

import { createContext, useContext, useEffect, useState } from 'react'

const ThemeContext = createContext()

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState(() => {
    return localStorage.getItem('theme') || 'light'
  })

  useEffect(() => {
    if (theme === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
    localStorage.setItem('theme', theme)
  }, [theme])

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  )
}

export function ThemeToggle() {
  const { theme, setTheme } = useContext(ThemeContext)

  return (
    <button
      onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
      className="px-4 py-2 rounded-lg bg-gray-200 dark:bg-gray-800"
    >
      {theme === 'light' ? '🌙' : '☀️'}
    </button>
  )
}

Рекомендации

  • Сохраняй выбор в localStorage
  • Обнаруживай системную тему как fallback
  • Используй CSS переменные для простоты
  • Добавляй плавные переходы между темами
  • Тестируй на контрастность для доступности
Как сервер вернет ответ на запрос если ему не нравится CORS? | PrepBro