1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CORSエラーの原因がPHPの設定変更だった

Last updated at Posted at 2020-12-20

自作アプリを作成している際に発生した fetch による CORS エラーの原因が、
単なる PHP 設定変更だったというお話です。

内容

React から fetch による PHP へのデータ送信処理を実行したところ、
CORSエラーが発生しました。

Access to fetch at 'http://localhost/hoge.php' from origin 
'http://localhost:3000' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
If an opaque response serves your needs, set the request's mode to 
'no-cors' to fetch the resource with CORS disabled.

React の fetch 処理は下記の通り。

const response = await fetch(
    "http://localhost/hoge.php",
    {
       method: "POST",
       body: JSON.stringify(values),
    }
);

最初は
「header("Access-Control-Allow-Origin: *") つけ忘れかな?」
と思ったけど、PHP 側のファイルを見たら記述されていました。

PHP 側の header 部分:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
header("Content-type:application/json");

「ちゃんと記述しているのになんでCORSエラーが出るんだ😡」
と思って、試しにデータ送信先を「存在しないファイル」である hoge2.php に変更したところ同じエラーが発生。

Access to fetch at 'http://localhost/hoge2.php' from origin 
'http://localhost:3000' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
If an opaque response serves your needs, set the request's mode to 
'no-cors' to fetch the resource with CORS disabled.

ここで
「もしかしてファイルが読み込めてないとか?PHPの設定が問題?」
と思い調査。

・localhost で It works! が表示されるかチェック
 問題なし。

・phpmyadmin が繋がるかどうか
 403 error で繋がらない

「あれ、昨日まで phpmyadmin に繋がっていたのに・・・🤔 phpmyadmin.confの設定がおかしい?」

ここで /etc/apache2/other/phpmyadmin.conf を閲覧したところ、
phpmyadmin.conf に記述していた下記内容が消えていました。

<Location /phpmyadmin>                                                                              
    Order deny,allow                                                                                
    Deny from all                                                                                   
    Allow from localhost                                                                            
</Location>  

さらに /etc/apache2/httpd.conf でも、有効にしていたはずの
LoadModule php7_module
がコメントアウトされていました。

これらを元に戻したところ、無事 CORS エラーが発生しなくなりました。

原因

原因はおそらく MacOS のアップデート(v10 から v11)ではないかと思ってます。
設定が勝手に変更されるような事で思い当たるのがそれくらいなので・・・。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?