CORS: Origin is not allowed
CORSエラーでリクエストがブロックされた場合の原因と解決策
概要
異なるオリジン間でのリクエストがCORSポリシーによりブロックされるエラーです。
エラーメッセージ
``` Access to fetch at ‘https://api.example.com/data' from origin ‘https://app.example.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. ```
原因
- サーバー側のCORS設定なし: Access-Control-Allow-Origin未設定
- 許可されていないオリジン: ホワイトリストに含まれない
- Preflightリクエストの失敗: OPTIONSリクエストが拒否
- 認証情報の送信: credentials設定の不一致
解決策
1. Express.js (Node.js)
```javascript const cors = require(‘cors’);
// 全オリジン許可(開発環境向け) app.use(cors());
// 特定オリジンのみ許可(本番環境向け) app.use(cors({ origin: [‘https://app.example.com’, ‘https://admin.example.com’], methods: [‘GET’, ‘POST’, ‘PUT’, ‘DELETE’], allowedHeaders: [‘Content-Type’, ‘Authorization’], credentials: true })); ```
2. Django
```python
settings.py
INSTALLED_APPS = [ ‘corsheaders’, … ]
MIDDLEWARE = [ ‘corsheaders.middleware.CorsMiddleware’, # 最初に配置 ‘django.middleware.common.CommonMiddleware’, … ]
CORS_ALLOWED_ORIGINS = [ ‘https://app.example.com’, ]
または全許可(開発環境)
CORS_ALLOW_ALL_ORIGINS = True ```
3. Laravel
```php // config/cors.php return [ ‘paths’ => [‘api/’], ‘allowed_methods’ => [’’], ‘allowed_origins’ => [‘https://app.example.com’], ‘allowed_headers’ => [’*’], ‘supports_credentials’ => true, ]; ```
4. Nginx
```nginx location /api { if ($request_method = ‘OPTIONS’) { add_header ‘Access-Control-Allow-Origin’ ‘https://app.example.com’; add_header ‘Access-Control-Allow-Methods’ ‘GET, POST, OPTIONS’; add_header ‘Access-Control-Allow-Headers’ ‘Authorization, Content-Type’; add_header ‘Access-Control-Max-Age’ 86400; return 204; }
add_header 'Access-Control-Allow-Origin' 'https://app.example.com' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
proxy_pass http://backend;
} ```
5. クライアント側の設定
```javascript // credentials が必要な場合 fetch(‘https://api.example.com/data', { method: ‘GET’, credentials: ‘include’, // Cookie送信 headers: { ‘Content-Type’: ‘application/json’, } }); ```
6. AWS API Gateway
```yaml
serverless.yml
functions: api: handler: handler.main events: - http: path: /data method: get cors: origin: ‘https://app.example.com’ headers: - Content-Type - Authorization allowCredentials: true ```
よくある間違い
- Access-Control-Allow-Origin: * と credentials: true の併用
- OPTIONSメソッドのハンドリング忘れ
- プロキシ経由でヘッダーが削除される
関連エラー
関連エラー
Web の他のエラー
この記事は役に立ちましたか?