Eldar Tailov
Eldar Tailov

Reputation: 378

How correctly to use interceptorce with axios + react

Here is my instance of axios in react app. What I want to do is to catch errors from server and base on error silence it. For instance if user with this name is existed I want to silence error and just return alert message. But interceptor doesn't trigger:

import axios from "axios";

const instance = axios.create({
    baseURL: "http://localhost:8000",
    withCredentials: true,
    timeout: 1000
})

instance.interceptors.request.use(
    request => request,
    error => {
        console.log(error)
        console.log(error.response)
        console.log(error.response.message)
        return { data: {  status: 'fail' } };
    }
)

export default instance

For now I just want console.log it, but it still breaks the whole logic and throws an error ((

Upvotes: 0

Views: 899

Answers (2)

linchong
linchong

Reputation: 483

request interceptor (axios.interceptors.request.use) is generally used to configure parameters in the header, such like

instance.interceptors.request.use(config => {
  console.log('request interceptor in here')
  config.headers = {
    ...config.headers,
    'x-requested-with': 'XMLHttpRequest'
    // other parameters...
  }
  return config
})

and the response interceptor (axios.interceptors.response.use) to intercept returned results or errors, such like

instance.interceptors.response.use(response => {
  console.log('success', response)
}, error => {
  console.log('fail', error)
})

Upvotes: 1

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

You should use a response interceptor (axios.interceptors.response.use) to intercept responses and handle errors.

instance.interceptors.response.use(
  (response) => response,
  (error) => {
    console.log(error)
    // ...
  }
)

Upvotes: 1

Related Questions