CORSエラーの原因と直し方(エラーメッセージ別)

WEB
スポンサーリンク

ブラウザのコンソールに出るCORSのエラーを、メッセージごとに原因と直し方へ対応させた記事です。よくある原因を小さなサーバーで1つずつ起こし、ブラウザに実際に出たエラーを載せています。

結論

Chrome系のブラウザ(Chromium)のコンソールに出たメッセージと、サーバー側の直し方です。ページのオリジンは http://localhost:18001、APIは http://localhost:18002 です。

メッセージ(has been blocked by CORS policy: の後)原因直し方(APIのレスポンスヘッダー)
No 'Access-Control-Allow-Origin' header is present on the requested resource.レスポンスに Access-Control-Allow-Origin がないAccess-Control-Allow-Origin: http://localhost:18001
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.プリフライト(OPTIONS)のレスポンスが、成功のステータスでなく、CORSのヘッダーもないOPTIONS に成功のステータス(今回は204)と、Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers を返す
Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.プリフライトで、使うメソッドを許可していないAccess-Control-Allow-Methods: GET, POST, PUT
Request header field x-api-key is not allowed by Access-Control-Allow-Headers in preflight response.プリフライトで、送るヘッダーを許可していないAccess-Control-Allow-Headers: Content-Type, X-Api-Key
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.資格情報つき(credentials: 'include')なのに * を返している* ではなく、ページのオリジンを書く
The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.資格情報つきなのに Access-Control-Allow-Credentials がないAccess-Control-Allow-Credentials: true
  • CORSの制限はブラウザがかけています。直すのは、呼び出される側(API)のレスポンスヘッダーです。
  • JavaScriptの catch で受け取れるのは TypeError: Failed to fetch(Chromium)だけで、原因は分かりません。原因はブラウザの開発者ツールのコンソールで見ます。
  • プリフライトがないリクエスト(今回はGET)は、エラーになってもサーバーに届いて処理されていました。ブラウザが止めたのは、レスポンスをJavaScriptで読むことです。
  • curlにはCORSの制限がないので、curlで成功してもブラウザで成功するとは限りません。

動作確認した環境

  • Dockerイメージ: mcr.microsoft.com/playwright:v1.64.1-noble(Ubuntu 24.04、Node.js 26.13.0)
  • ブラウザ: このイメージの中のヘッドレスのChromium 156.0.8078.80 とFirefox 157.0(Playwright 1.64.1 で操作)
  • ホスト: Windows 11、Docker 29.7.2(Docker Desktop)、PowerShell 7.6.5、Windows PowerShell 5.1、curl 8.21.0
  • 確認日: 2026年11月5日

この記事は、MacとWindowsの両方の読者を対象にしています。サーバーはDockerのコンテナで動かすので、MacでもWindowsでも同じ手順です。OSで書き方が違うコマンドは、両方を載せています。

この記事の内容は、Claude(AI)が実行して確認しました。ブラウザは、普段使うChromeやFirefoxではなく、コンテナの中のLinux版のヘッドレスブラウザです。コンソールのメッセージは、Playwrightでブラウザのコンソールの表示を取得したものです。CORSの判定はOSによらない想定ですが、MacとWindowsのブラウザでは確認していません。Macのコマンド($ で始まるもの)も実行していません。

準備

空のフォルダに、次の2つのファイルを置きます。server.js は、ページ(ポート18001)とAPI(ポート18002)を返すサーバーです。APIはパスごとに、返すCORSのヘッダーを変えています。Node.jsの標準機能だけで動きます。

// CORS の確認用サーバー(Node.js の標準機能だけで動く)
// ページ: http://localhost:18001  API: http://localhost:18002
const http = require('node:http');
const fs = require('node:fs');

const PAGE_ORIGIN = 'http://localhost:18001';

// ページを返すサーバー
http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(18001);

// API のサーバー。パスごとに、返す CORS のヘッダーを変える
http.createServer((req, res) => {
  const path = new URL(req.url, 'http://localhost').pathname;
  console.log(`${req.method} ${path} Origin: ${req.headers.origin ?? '-'}`);

  const h = {};
  switch (path) {
    case '/no-header': // CORS のヘッダーを付けない
      break;
    case '/simple-ok':
      h['Access-Control-Allow-Origin'] = PAGE_ORIGIN;
      break;
    case '/no-preflight': // OPTIONS(プリフライト)に答えない
      if (req.method === 'OPTIONS') { res.writeHead(404); return res.end(); }
      h['Access-Control-Allow-Origin'] = PAGE_ORIGIN;
      break;
    case '/method-missing': // PUT を許可していない
      h['Access-Control-Allow-Origin'] = PAGE_ORIGIN;
      h['Access-Control-Allow-Methods'] = 'GET, POST';
      h['Access-Control-Allow-Headers'] = 'Content-Type';
      break;
    case '/header-missing': // X-Api-Key を許可していない
      h['Access-Control-Allow-Origin'] = PAGE_ORIGIN;
      h['Access-Control-Allow-Methods'] = 'GET, POST, PUT';
      h['Access-Control-Allow-Headers'] = 'Content-Type';
      break;
    case '/preflight-ok':
      h['Access-Control-Allow-Origin'] = PAGE_ORIGIN;
      h['Access-Control-Allow-Methods'] = 'GET, POST, PUT';
      h['Access-Control-Allow-Headers'] = 'Content-Type, X-Api-Key';
      break;
    case '/cred-wildcard': // 資格情報つきなのに * を返す
      h['Access-Control-Allow-Origin'] = '*';
      h['Access-Control-Allow-Credentials'] = 'true';
      break;
    case '/cred-no-allow': // Access-Control-Allow-Credentials を付けない
      h['Access-Control-Allow-Origin'] = PAGE_ORIGIN;
      break;
    case '/cred-ok':
      h['Access-Control-Allow-Origin'] = PAGE_ORIGIN;
      h['Access-Control-Allow-Credentials'] = 'true';
      h['Vary'] = 'Origin';
      break;
  }

  if (req.method === 'OPTIONS') { res.writeHead(204, h); return res.end(); }
  res.writeHead(200, { ...h, 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ ok: true, path }));
}).listen(18002);

console.log('page: http://localhost:18001  api: http://localhost:18002');

index.html は、URLの ?case= で指定したケースのリクエストをAPIに送り、結果を画面に出すページです。

<!doctype html>
<meta charset="utf-8">
<title>CORS check</title>
<pre id="result"></pre>
<script>
const API = 'http://localhost:18002';
const json = { 'Content-Type': 'application/json' };
const cases = {
  'no-header':      () => fetch(`${API}/no-header`),
  'simple-ok':      () => fetch(`${API}/simple-ok`),
  'no-preflight':   () => fetch(`${API}/no-preflight`, { method: 'PUT', headers: json, body: '{}' }),
  'method-missing': () => fetch(`${API}/method-missing`, { method: 'PUT', headers: json, body: '{}' }),
  'header-missing': () => fetch(`${API}/header-missing`, { method: 'PUT', headers: { ...json, 'X-Api-Key': 'abc' }, body: '{}' }),
  'preflight-ok':   () => fetch(`${API}/preflight-ok`, { method: 'PUT', headers: { ...json, 'X-Api-Key': 'abc' }, body: '{}' }),
  'cred-wildcard':  () => fetch(`${API}/cred-wildcard`, { credentials: 'include' }),
  'cred-no-allow':  () => fetch(`${API}/cred-no-allow`, { credentials: 'include' }),
  'cred-ok':        () => fetch(`${API}/cred-ok`, { credentials: 'include' }),
};
const name = new URLSearchParams(location.search).get('case');
const out = document.getElementById('result');
cases[name]()
  .then(async (r) => { out.textContent = `OK ${r.status} ${await r.text()}`; })
  .catch((e) => { out.textContent = `NG ${e.name}: ${e.message}`; });
</script>

そのフォルダでサーバーを起動します。Node.jsは、Playwrightのイメージに入っているものを使います。今いるフォルダの書き方だけ、OSで違います。

Macの $(pwd) は、Dockerの公式ドキュメントのバインドマウントの例と同じ書き方です。

# Windows(PowerShell 7 で実行。Windows PowerShell 5.1 でも -v "${PWD}:/work" でフォルダが見えることを確認)
PS> docker run -d --name cors-lab -p 18001:18001 -p 18002:18002 -v "${PWD}:/work" -w /work mcr.microsoft.com/playwright:v1.64.1-noble node server.js

# Mac(未確認)
$ docker run -d --name cors-lab -p 18001:18001 -p 18002:18002 -v "$(pwd):/work" -w /work mcr.microsoft.com/playwright:v1.64.1-noble node server.js

ブラウザで http://localhost:18001/?case=no-header のように開き、開発者ツールのコンソールを見ます。サーバーが受け取ったリクエストは docker logs cors-lab で見られます。終わったら docker rm -f cors-lab で消します。

以降の出力は、準備のあとにケースを上から順に開いた結果です。「ページ」は画面に出た結果、「サーバーのログ」はそのケースで docker logs に増えた行です。

ケース別のエラーと直し方

Access-Control-Allow-Origin がない

?case=no-header です。APIがCORSのヘッダーを返さないと、次のエラーになりました。

[コンソール]
Access to fetch at 'http://localhost:18002/no-header' from origin 'http://localhost:18001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED
[ページ]
NG TypeError: Failed to fetch
[サーバーのログ]
GET /no-header Origin: http://localhost:18001

サーバーのログを見ると、GETはサーバーに届いていて、サーバーは200を返しています(後半のcurlで確認)。ブラウザは、レスポンスにページのオリジンの許可がないので、JavaScriptに結果を渡しませんでした。サーバーで処理は実行されるので、CORSは「サーバーをリクエストから守る仕組み」ではない点に注意します。

直し方は、Access-Control-Allow-Origin にページのオリジンを書くことです(?case=simple-ok)。

[ページ]
OK 200 {"ok":true,"path":"/simple-ok"}

プリフライト(OPTIONS)に答えていない

PUT や、Content-Type: application/json のリクエストでは、ブラウザが先に OPTIONS のリクエスト(プリフライト)を送って、許可を確かめます。プリフライトがいらないのは、メソッドが GET、HEAD、POST のどれかで、Content-Type を指定するならその値が application/x-www-form-urlencoded、multipart/form-data、text/plain のどれかである、などの条件を満たすときだけです(MDN)。

?case=no-preflight では、APIが OPTIONS に404を返します。

[コンソール]
Access to fetch at 'http://localhost:18002/no-preflight' from origin 'http://localhost:18001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED
[ページ]
NG TypeError: Failed to fetch
[サーバーのログ]
OPTIONS /no-preflight Origin: http://localhost:18001

サーバーのログには OPTIONS しかなく、本来の PUT は送られていません。プリフライトで止まったときは、本来のリクエストはサーバーに届きません。メッセージに preflight とあるときは、OPTIONS のレスポンスを見直します。

プリフライトのレスポンスには、CORSのヘッダーに加えて、200〜299の成功のステータスが必要です(Fetch Standard)。CORSのヘッダーだけを足しても、404のままでは通りません。成功させる例は、この後の ?case=preflight-ok です(OPTIONS に204とCORSのヘッダーを返します)。

メソッドを許可していない

?case=method-missing では、プリフライトのレスポンスの Access-Control-Allow-Methods が GET, POST で、PUT がありません。

[コンソール]
Access to fetch at 'http://localhost:18002/method-missing' from origin 'http://localhost:18001' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
Failed to load resource: net::ERR_FAILED
[ページ]
NG TypeError: Failed to fetch
[サーバーのログ]
OPTIONS /method-missing Origin: http://localhost:18001

リクエストヘッダーを許可していない

?case=header-missing では、ページが独自のヘッダー X-Api-Key を送りますが、Access-Control-Allow-Headers は Content-Type だけです。

[コンソール]
Access to fetch at 'http://localhost:18002/header-missing' from origin 'http://localhost:18001' has been blocked by CORS policy: Request header field x-api-key is not allowed by Access-Control-Allow-Headers in preflight response.
Failed to load resource: net::ERR_FAILED
[ページ]
NG TypeError: Failed to fetch
[サーバーのログ]
OPTIONS /header-missing Origin: http://localhost:18001

メソッドに PUT、ヘッダーに X-Api-Key を加えると(?case=preflight-ok)、プリフライトの後に本来の PUT が送られ、成功しました。

[ページ]
OK 200 {"ok":true,"path":"/preflight-ok"}
[サーバーのログ]
OPTIONS /preflight-ok Origin: http://localhost:18001
PUT /preflight-ok Origin: http://localhost:18001

資格情報つきのリクエストに * を返している

Cookieを送るために credentials: 'include' をつけたリクエストでは、Access-Control-Allow-Origin に * は使えません(MDN)。?case=cred-wildcard では、* と Access-Control-Allow-Credentials: true を返しています。

[コンソール]
Access to fetch at 'http://localhost:18002/cred-wildcard' from origin 'http://localhost:18001' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
Failed to load resource: net::ERR_FAILED
[ページ]
NG TypeError: Failed to fetch
[サーバーのログ]
GET /cred-wildcard Origin: http://localhost:18001

Access-Control-Allow-Credentials がない

?case=cred-no-allow では、オリジンは正しく書いていますが、Access-Control-Allow-Credentials を返していません。

[コンソール]
Access to fetch at 'http://localhost:18002/cred-no-allow' from origin 'http://localhost:18001' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
Failed to load resource: net::ERR_FAILED
[ページ]
NG TypeError: Failed to fetch
[サーバーのログ]
GET /cred-no-allow Origin: http://localhost:18001

オリジンを書き、Access-Control-Allow-Credentials: true を返すと(?case=cred-ok)、成功しました。値は true だけが有効です(MDN)。また、リクエストのオリジンによって Access-Control-Allow-Origin を変える場合は、キャッシュが混ざらないように Vary: Origin も返します(MDN)。

[ページ]
OK 200 {"ok":true,"path":"/cred-ok"}

Firefoxのメッセージ

Firefox 157.0 でも、同じケースはすべて同じ結果(失敗と成功)になりました。メッセージの文言は違います。ページに出たエラーは TypeError: NetworkError when attempting to fetch resource. でした。コンソールのメッセージの Reason: の部分は次のとおりです。

ケースFirefoxの Reason
no-headerCORS header ‘Access-Control-Allow-Origin’ missing
no-preflightCORS header ‘Access-Control-Allow-Origin’ missing(Status code: 404)と CORS request did not succeed
method-missingDid not find method in CORS header ‘Access-Control-Allow-Methods’
header-missingheader ‘x-api-key’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response
cred-wildcardCredential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’
cred-no-allowexpected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’

curlで確かめる

ブラウザでエラーになった /no-header も、curlでは普通にレスポンスが返ります。curlはCORSの判定をしないためです。ブラウザと同じように Origin ヘッダーをつけても同じでした。

この章のコマンドは、WindowsのPowerShellで実行したものです。Macのターミナルでは、curl.exe を curl に置き換えます。オプション(-s、-i、-X、-H)はcurlのマニュアルのとおりで、OSによりません。Macでは実行していません。

PS> curl.exe -s -i -H "Origin: http://localhost:18001" http://localhost:18002/no-header
HTTP/1.1 200 OK
Content-Type: application/json
Date: Thu, 05 Nov 2026 11:26:09 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

{"ok":true,"path":"/no-header"}

そのかわり、curlでプリフライトと同じリクエストを送ると、サーバーが返すCORSのヘッダーを直接確かめられます。ブラウザのエラーの原因を、サーバー側で切り分けるときに使えます。/header-missing では、Access-Control-Allow-Headers に X-Api-Key がないことが分かります。

PS> curl.exe -s -i -X OPTIONS -H "Origin: http://localhost:18001" -H "Access-Control-Request-Method: PUT" -H "Access-Control-Request-Headers: content-type,x-api-key" http://localhost:18002/header-missing
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:18001
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type
Date: Thu, 05 Nov 2026 11:26:09 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Windows PowerShell 5.1 の curl は curl ではない

Windows PowerShell 5.1 では、curl は Invoke-WebRequest の別名で、curlのオプションが使えませんでした。PowerShell 7.6 では、curl はWindowsに入っている curl.exe を指していました。どちらでも動くように、Windowsでは curl.exe と書きます。

PS> curl -i -H "Origin: http://localhost:18001" http://localhost:18002/no-header
Invoke-WebRequest : Missing an argument for parameter 'InFile'. Specify a parameter of type 'System.String' and try aga
in.

Macでは curl と書きます(Macでは未確認)。比較のため、1つ目のコマンドは、コンテナの中のLinuxの curl(8.5.0)でも実行し、同じレスポンスが返ることを確かめました。2つ目はLinuxでは実行していません。

$ curl -s -i -H "Origin: http://localhost:18001" http://localhost:18002/no-header
$ curl -s -i -X OPTIONS -H "Origin: http://localhost:18001" -H "Access-Control-Request-Method: PUT" -H "Access-Control-Request-Headers: content-type,x-api-key" http://localhost:18002/header-missing

参考

スポンサーリンク
WEB
スポンサーリンク
シェアする
hayoをフォローする

コメント

タイトルとURLをコピーしました