在vuejs axios中设置拦截器

时间:2017-11-22 07:46:14

标签: javascript vuejs2

我用拦截器设置axios

const axiosConfig = {
    baseURL: 'http://127.0.0.1:8000/api',
    timeout: 30000
};

axios.interceptors.response.use((response) => { // intercept the global error
    console.log("response is", response);
    return response
}, (error) => {
    console.log("errors are", error);
    if (error.response.status === 401) {
        // if the error is 401 and hasent already been retried
        alert("You will need to login to access this");
        window.location.href = '/auth/login'
        return
    }
    if (error.response.status === 404) {
        window.location.href = '/'
        return
    }
});

Vue.prototype.$axios = axios.create(axiosConfig)

但上述拦截器不起作用。我哪里出错了? console.log()消息无法正常工作。

1 个答案:

答案 0 :(得分:0)

我发送给你最小的工作示例,说明如何在请求开始之前拦截ajax。我在页面上有一个按钮,然后我绑定它来拉取一些数据,但在此之前我有console.log'ed拦截器消息=>你可以用你的逻辑代替它。

希望可以帮助你开始..

// let's intercept axios ajax call BEFORE it starts
var INTER = axios.interceptors.request.use(
  function(config){ console.log('intercepted!'); return config;},
  function(error){return Promise.reject(error);}
);
// function to pull remote data
function pullData(){
  var url = 'https://jsonplaceholder.typicode.com/posts';
  axios.get( url )
  .then(function (response) {
    console.log(response.status);
  })
  .catch(function (error) { console.log(error); });
}

// reff the button on the page
var b = document.getElementById('b');
// bind to click event
b.addEventListener('click', pullData, false);
<script src="https://unpkg.com/vue@2.5.8/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios@0.17.1/dist/axios.min.js"></script>

<button id="b">Click to pull http req resource</button>