You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中Safari调用API返回401但Chrome正常的问题求助

Troubleshooting Safari-Specific 401 Error with React + Axios + Django REST Framework

Hey there, let's tackle this frustrating Safari-only 401 issue you're hitting. Since Chrome and Postman work fine, it's definitely a quirk in how Safari handles requests—let's break down the most likely fixes:

1. Confirm the Auth Token is Actually Being Sent in Safari

First, let's rule out the basics: open Safari's Developer Tools (enable it via Settings > Advanced > Show Develop menu), head to the Network tab, and inspect the headers of your failing GET request.

  • If the Authorization header is missing or has an invalid token, your axios setup might behave differently in Safari. Add a quick console log in your request interceptor to verify the token is being retrieved correctly:
    axios.interceptors.request.use(config => {
      const token = localStorage.getItem('authToken');
      console.log('Token retrieved in Safari:', token); // Check this in Safari's console
      if (token) {
        config.headers.Authorization = `Token ${token}`;
      }
      return config;
    });
    

2. Disable Safari's Aggressive GET Request Caching

Safari caches GET requests way more aggressively than Chrome—even ones that require authentication. If an unauthenticated version of your request was cached earlier, Safari might reuse that instead of sending your new authenticated request.

Fix this by adding cache-control headers to your GET requests:

axios.get('/your-api-endpoint', {
  headers: {
    'Cache-Control': 'no-cache, no-store, must-revalidate',
    'Pragma': 'no-cache',
    'Expires': '0'
  }
});

You can also set this globally in axios to apply to all requests:

axios.defaults.headers.common['Cache-Control'] = 'no-cache, no-store, must-revalidate';

If you're using session authentication or storing tokens in cookies, Safari enforces stricter rules for cookie attributes than Chrome. Update your Django settings to make cookies cross-domain-friendly:

# settings.py
SESSION_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
CORS_ALLOW_CREDENTIALS = True

Note: SameSite=None requires the Secure flag, so this only works if your frontend and backend are served over HTTPS (standard for production). For local development, use 'Lax' instead.

4. Check LocalStorage Access in Safari's Private Mode

Safari's Private Browsing mode restricts localStorage access—it acts as a read-only store, or may throw errors when writing to it. If your app relies on localStorage for token storage, test in normal Safari mode first. If it works there but fails in Private Mode, consider switching to sessionStorage or adjusting your token storage strategy.

5. Verify Axios withCredentials Configuration

If you're passing credentials via cookies (not just headers), make sure axios has withCredentials enabled—either globally or per request:

// Global setup
axios.defaults.withCredentials = true;

// Or per request
axios.get('/your-api-endpoint', { withCredentials: true });

And double-check that your Django CORS config allows credentials (we already set CORS_ALLOW_CREDENTIALS = True above).


内容的提问来源于stack exchange,提问作者Makai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:14:54