LoginSignup
9
4

More than 5 years have passed since last update.

railsアプリ fetchを使ったajax通信のエラーハンドリングで気をつけること

Last updated at Posted at 2017-04-20

RailsとReact.jsを使ってアプリ開発時に、fetchを使ったajax通信のエラーハンドリングで気づきがあったのでメモします。


railsアプリにおいて、以下のようにrequest.xhr?で条件分岐をし、ajax通信時とそれ以外という形でエラーハンドリングをすることは良くあるかと思います。

application_controller.rb
 rescue_from ActionController::RoutingError,   with: :_render_404

 private

 def _render_404(e = nil)
   logger.info "Rendering 404 with exception: #{e.message}" if e
   if request.xhr?
     render json: { error: '404 error' }, status: :not_found, layout: false
   else
    render template: 'errors/error_404', status: 404, layout: 'application'
  end

Railsのxhr?メソッドは
request.xhr? #=> 0 or nil
@env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"の結果を返しています。
しかし、fetchを使った場合のrequest.headerには'X-Requested-With': 'XMLHttpRequest'が含まれないのでそれがajax通信なのかどうかは判断出来ないようです。

なので、fetchを使用する時は、headerに以下を追加してあげることで、jQueryの$.ajaxなどと同じようにRailsのxhr?でajax通信かどうかを判断出来るようになります。

headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrfToken,
      'X-Requested-With': 'XMLHttpRequest',
    },

参考

Fetch API - Web API インターフェイス | MDN
github/fetch#17
http://stackoverflow.com/questions/33662318/how-do-i-detect-requests-initiated-by-the-new-fetch-standard-how-should-i-detec

9
4
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
9
4