LoginSignup
83
53

More than 3 years have passed since last update.

axiosのinterceptorsで、リクエストの前処理を共通して行う

Posted at

axiosを使ってAPIリクエストを送る際に、前処理を行いたいケースがありました。
リクエストを送る前に毎回処理を記載する方法もあるのですが、interceptorsを使用することで綺麗に書けそうだったので調べてみました。

interceptorsとは

interceptは途中で捕まえるといった意味のようです。

You can intercept requests or responses before they are handled by then or catch.

リクエストを送る前にログを出してみる

interceptorsを使用して、毎回リクエストとレスポンスの前にログを出力させてみます。

import axios from 'axios';

axios.interceptors.request.use(request => {
  console.log(request.url)
  return request
})

axios.interceptors.response.use(response => {
  console.log(response.url)
  return response
})


axios.post('/path')
.then(() => {
  console.log('ok')
})
.catch(() => {
  console.log('ng')
})

// /path
// 200
// ok

下記の順番で出力されていることがわかりました。
1. interceptors.requestのログ
2. interceptors.responseのログ
3. then()のログ

実際にはパラメータやパスなどに処理を加える

実際に使う場合には、このようにリクエストを送る前処理を共通化させる場合などに使えると思います。

axios.interceptors.request.use(request => {
  JSON.stringify(request.data)
  return request
})
83
53
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
83
53