Help us understand the problem. What is going on with this article?

rails の request.xhr?メソッドと axios でのajax通信

More than 1 year has passed since last update.

これまで ajax通信には jQery 使ってたけど、axios にでajax通信するようになって少しハマったのでメモ

request.xhr? とは?

リクエストが XMLHttpRequest(いわゆるajax通信)かどうか判定するメソッド。
リクエストがajaxかどうかで処理を分岐させる時によく使う。

ハマったこと

今回 axios でajax通信を行なった時に request.xhr?false を返してきた。

原因

request.xhr?コードは以下のように定義されている

def xml_http_request?
  get_header("HTTP_X_REQUESTED_WITH") =~ /XMLHttpRequest/i
end
alias :xhr? :xml_http_request?

やってることはすごく単純で HTTP_X_REQUESTED_WITHヘッダーXMLHttpRequest が含まれているかどうかを見てるだけ。

対して

axios.get('/hogehoge')

のようにajax通信を行なってもHTTP_X_REQUESTED_WITHヘッダーはつかない。
よってrequest.xhr? が必ず false を返す。

どうすれば良いか

単純にHTTP_X_REQUESTED_WITHヘッダー を明示的に指定すれば良い。
こんな感じ

axios.get('/hogehoge', headers: {'X-Requested-With': 'XMLHttpRequest'})
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away