MeWrite Docs

CORS: preflight request failed

CORSプリフライトリクエストエラーの解決方法

概要

ブラウザのCORSプリフライトリクエスト(OPTIONS)が失敗した場合に発生するエラーです。

エラーメッセージ

Access to fetch at 'https://api.example.com' from origin 'https://myapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check

原因

  1. OPTIONSメソッド未対応: サーバーがOPTIONSに応答しない
  2. ヘッダー不足: 必要なCORSヘッダーがない
  3. 認証情報の扱い: credentialsモードとワイルドカード
  4. カスタムヘッダー: 許可されていないヘッダー

解決策

1. Express.js

1
2
3
4
5
6
7
8
const cors = require('cors');

app.use(cors({
  origin: 'https://myapp.com',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

2. 手動設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'https://myapp.com');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.header('Access-Control-Allow-Credentials', 'true');

  if (req.method === 'OPTIONS') {
    return res.status(204).end();
  }
  next();
});

3. Nginx

1
2
3
4
5
6
7
8
9
location /api {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' 'https://myapp.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        add_header 'Access-Control-Max-Age' 86400;
        return 204;
    }
}

よくある間違い

  • credentials: trueとorigin: ‘*‘の組み合わせ
  • プリフライトキャッシュの設定忘れ

最終更新: 2025-12-09