1
0

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.

axios では xhr? が効かない

Posted at

自分用メモ。

axiosはAjaxで通信するときに、リクエストヘッダーにX-Requested-Withを付けません。

参照: https://github.com/axios/axios/issues/1322

なので、Railsのxhr?メソッドは偽になります。

if request.xhr?
 # axiosだと効かない
end

xhr?メソッドを使いたければ、JavaScript側でaxiosのヘッダーにX-Requested-Withを追加する設定が必要です。

Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

あるいは、Rails側でX-Requested-Withがなくても動くようにします。

if params[:format] == 'json'
 # Ajaxの場合の処理
end
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?