サーバー側をLaravel、クライアント側をReactで構築しています。
サーバー側では、api.hoge
というドメインでをAPI用に割当て、クライアント側は、admin.hoge
ドメインを割り当ててAPIとは別ドメインで運用しています。
サーバー側レスポンスヘッダの設定は、LaravelでCorsというミドルウェアを定義し、apiのルーティングにcorsミドルウェアを通すように設定しています。
<?php namespace App\Http\Middleware; use Closure; class Cors { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { return $next($request) ->header('Access-Control-Allow-Origin', 'http://admin.hoge') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD') ->header('Access-Control-Allow-Credentials', 'true') ->header('Access-Control-Max-Age', '1000') ->header('Origin', 'Access-Control-Allow-Headers', 'Accept', 'Content-Type, X-Requested-With'); } }
クライアント側では、axiosで以下のようにリクエストしています。
リクエストヘッダのデフォルト設定を定義 // const api = axios.create({ baseURL: 'http://api.hoge/v1', timeout: 10000, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }); export function createCategory(props) { const request = api.post(`/categories`, props); return {type: CREATE_CATEGORY, payload: request}; }
postのapiをコールした時に以下のようなエラーがでます。
XMLHttpRequest cannot load http://api.hoge/v1/categories. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
エラーが出た時のヘッダー情報は以下の通りです。
preflightのoptionメソッドのリクエストで止まるため、postが動作していない状態です。
Request URL:http://api.hoge/v1/categories Request Method:OPTIONS Status Code:200 OK Remote Address:192.168.33.111:80 Referrer Policy:no-referrer-when-downgrade Response Headers view source Access-Control-Allow-Credentials:true Access-Control-Allow-Methods:GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD Access-Control-Allow-Origin:http://admin.hoge Access-Control-Max-Age:1000 Allow:GET,HEAD,POST Cache-Control:no-cache Connection:keep-alive Content-Type:text/html; charset=UTF-8 Date:Tue, 25 Apr 2017 09:39:07 GMT Origin:Access-Control-Allow-Headers Server:nginx/1.10.2 Transfer-Encoding:chunked X-Powered-By:PHP/7.0.17 Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:ja,en-US;q=0.8,en;q=0.6 Access-Control-Request-Headers:content-type Access-Control-Request-Method:POST Connection:keep-alive Host:api.hoge Origin:http://admin.hoge Referer:http://admin.hoge/dashboard/categories User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36 Name categories api.hoge/v1
※ブラウザはchromeを使っています。
get
やdelete
のメソッドの場合は問題ないのですが、post
やpatch
の時だけエラーがでます。
どこに問題があるのでしょうか??
調査方法や解決策を教えて頂けますと幸いです。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。