“Axios Interceptors” Kode Jawaban

Axios mendapatkan kode status

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });
Fusinato

Axios.Interceptors.Response.Use

// Add a response interceptor
HTTP.interceptors.response.use(function (response) {
 return response
}, function(error) {
 if (error.response.status === 401) {
  store.dispatch('logout')
  router.push('/login')
 }
 return Promise.reject(error.response.data)
})
Restu Wahyu Saputra

Minta respons interceptor axios

import axios from 'axios';
// const axios = require('axios');

// Step-1: Create a new Axios instance with a custom config.
// The timeout is set to 10s. If the request takes longer than
// that then the request will be aborted.
const customAxios = axios.create({
    baseURL: `https://example.com/api`,
    timeout: 10000, 
    headers: { 'api-key': 'eyJz-CI6Ikp-4pWY-lhdCI6' }
});

// Step-2: Create request, response & error handlers
const requestHandler = request => {
    // Token will be dynamic so we can use any app-specific way to always   
    // fetch the new token before making the call
    request.headers.Authorization = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIwMTIzNDU2Nzg5IiwibmFtZSI6IlNhbXBsZSIsImlhdCI6MTUxNjIzODIzfQ.ZEBwz4pWYGqgFJc6DIi7HdTN0z5Pfs4Lcv4ZNwMr1rs';  
  
    return request;
};

const responseHandler = response => {
    if (response.status === 401) {
        window.location = '/login';
    }

    return response;
};

const errorHandler = error => {
    return Promise.reject(error);
};

// Step-3: Configure/make use of request & response interceptors from Axios
// Note: You can create one method say configureInterceptors, add below in that,
// export and call it in an init function of the application/page.
customAxios.interceptors.request.use(
    (request) => requestHandler(request),
    (error) => errorHandler(error)
);

customAxios.interceptors.response.use(
    (response) => responseHandler(response),
    (error) => errorHandler(error)
 );


// Step-4: Export the newly created Axios instance to be used in different locations.
export default customAxios;

S4N705H

Axios Interceptors

	axios.interceptors.request.use((value) => {
		value.headers = {
			'Access-Control-Allow-Origin': '*',
			'Access-Control-Allow-Methods': '*',
			'Access-Control-Allow-Headers': '*',
			'Accept': 'application/json',
			'Content-Type': 'application/json'
		}
		return value
	})
Restu Wahyu Saputra

Jawaban yang mirip dengan “Axios Interceptors”

Pertanyaan yang mirip dengan “Axios Interceptors”

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya